Provide the HTLCs that settled a payment.
[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         user_channel_id: Option<u128>,
185         htlc_id: u64,
186         incoming_packet_shared_secret: [u8; 32],
187         phantom_shared_secret: Option<[u8; 32]>,
188
189         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
190         // channel with a preimage provided by the forward channel.
191         outpoint: OutPoint,
192 }
193
194 enum OnionPayload {
195         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
196         Invoice {
197                 /// This is only here for backwards-compatibility in serialization, in the future it can be
198                 /// removed, breaking clients running 0.0.106 and earlier.
199                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
200         },
201         /// Contains the payer-provided preimage.
202         Spontaneous(PaymentPreimage),
203 }
204
205 /// HTLCs that are to us and can be failed/claimed by the user
206 struct ClaimableHTLC {
207         prev_hop: HTLCPreviousHopData,
208         cltv_expiry: u32,
209         /// The amount (in msats) of this MPP part
210         value: u64,
211         /// The amount (in msats) that the sender intended to be sent in this MPP
212         /// part (used for validating total MPP amount)
213         sender_intended_value: u64,
214         onion_payload: OnionPayload,
215         timer_ticks: u8,
216         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
217         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
218         total_value_received: Option<u64>,
219         /// The sender intended sum total of all MPP parts specified in the onion
220         total_msat: u64,
221         /// The extra fee our counterparty skimmed off the top of this HTLC.
222         counterparty_skimmed_fee_msat: Option<u64>,
223 }
224
225 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
226         fn from(val: &ClaimableHTLC) -> Self {
227                 events::ClaimedHTLC {
228                         channel_id: val.prev_hop.outpoint.to_channel_id(),
229                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
230                         cltv_expiry: val.cltv_expiry,
231                         value_msat: val.value,
232                 }
233         }
234 }
235
236 /// A payment identifier used to uniquely identify a payment to LDK.
237 ///
238 /// This is not exported to bindings users as we just use [u8; 32] directly
239 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
240 pub struct PaymentId(pub [u8; 32]);
241
242 impl Writeable for PaymentId {
243         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
244                 self.0.write(w)
245         }
246 }
247
248 impl Readable for PaymentId {
249         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
250                 let buf: [u8; 32] = Readable::read(r)?;
251                 Ok(PaymentId(buf))
252         }
253 }
254
255 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
256 ///
257 /// This is not exported to bindings users as we just use [u8; 32] directly
258 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
259 pub struct InterceptId(pub [u8; 32]);
260
261 impl Writeable for InterceptId {
262         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
263                 self.0.write(w)
264         }
265 }
266
267 impl Readable for InterceptId {
268         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
269                 let buf: [u8; 32] = Readable::read(r)?;
270                 Ok(InterceptId(buf))
271         }
272 }
273
274 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
275 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
276 pub(crate) enum SentHTLCId {
277         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
278         OutboundRoute { session_priv: SecretKey },
279 }
280 impl SentHTLCId {
281         pub(crate) fn from_source(source: &HTLCSource) -> Self {
282                 match source {
283                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
284                                 short_channel_id: hop_data.short_channel_id,
285                                 htlc_id: hop_data.htlc_id,
286                         },
287                         HTLCSource::OutboundRoute { session_priv, .. } =>
288                                 Self::OutboundRoute { session_priv: *session_priv },
289                 }
290         }
291 }
292 impl_writeable_tlv_based_enum!(SentHTLCId,
293         (0, PreviousHopData) => {
294                 (0, short_channel_id, required),
295                 (2, htlc_id, required),
296         },
297         (2, OutboundRoute) => {
298                 (0, session_priv, required),
299         };
300 );
301
302
303 /// Tracks the inbound corresponding to an outbound HTLC
304 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
305 #[derive(Clone, PartialEq, Eq)]
306 pub(crate) enum HTLCSource {
307         PreviousHopData(HTLCPreviousHopData),
308         OutboundRoute {
309                 path: Path,
310                 session_priv: SecretKey,
311                 /// Technically we can recalculate this from the route, but we cache it here to avoid
312                 /// doing a double-pass on route when we get a failure back
313                 first_hop_htlc_msat: u64,
314                 payment_id: PaymentId,
315         },
316 }
317 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
318 impl core::hash::Hash for HTLCSource {
319         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
320                 match self {
321                         HTLCSource::PreviousHopData(prev_hop_data) => {
322                                 0u8.hash(hasher);
323                                 prev_hop_data.hash(hasher);
324                         },
325                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
326                                 1u8.hash(hasher);
327                                 path.hash(hasher);
328                                 session_priv[..].hash(hasher);
329                                 payment_id.hash(hasher);
330                                 first_hop_htlc_msat.hash(hasher);
331                         },
332                 }
333         }
334 }
335 impl HTLCSource {
336         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
337         #[cfg(test)]
338         pub fn dummy() -> Self {
339                 HTLCSource::OutboundRoute {
340                         path: Path { hops: Vec::new(), blinded_tail: None },
341                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
342                         first_hop_htlc_msat: 0,
343                         payment_id: PaymentId([2; 32]),
344                 }
345         }
346
347         #[cfg(debug_assertions)]
348         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
349         /// transaction. Useful to ensure different datastructures match up.
350         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
351                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
352                         *first_hop_htlc_msat == htlc.amount_msat
353                 } else {
354                         // There's nothing we can check for forwarded HTLCs
355                         true
356                 }
357         }
358 }
359
360 struct InboundOnionErr {
361         err_code: u16,
362         err_data: Vec<u8>,
363         msg: &'static str,
364 }
365
366 /// This enum is used to specify which error data to send to peers when failing back an HTLC
367 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
368 ///
369 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
370 #[derive(Clone, Copy)]
371 pub enum FailureCode {
372         /// We had a temporary error processing the payment. Useful if no other error codes fit
373         /// and you want to indicate that the payer may want to retry.
374         TemporaryNodeFailure,
375         /// We have a required feature which was not in this onion. For example, you may require
376         /// some additional metadata that was not provided with this payment.
377         RequiredNodeFeatureMissing,
378         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
379         /// the HTLC is too close to the current block height for safe handling.
380         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
381         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
382         IncorrectOrUnknownPaymentDetails,
383         /// We failed to process the payload after the onion was decrypted. You may wish to
384         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
385         ///
386         /// If available, the tuple data may include the type number and byte offset in the
387         /// decrypted byte stream where the failure occurred.
388         InvalidOnionPayload(Option<(u64, u16)>),
389 }
390
391 impl Into<u16> for FailureCode {
392     fn into(self) -> u16 {
393                 match self {
394                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
395                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
396                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
397                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
398                 }
399         }
400 }
401
402 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
403 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
404 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
405 /// peer_state lock. We then return the set of things that need to be done outside the lock in
406 /// this struct and call handle_error!() on it.
407
408 struct MsgHandleErrInternal {
409         err: msgs::LightningError,
410         chan_id: Option<([u8; 32], u128)>, // If Some a channel of ours has been closed
411         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
412         channel_capacity: Option<u64>,
413 }
414 impl MsgHandleErrInternal {
415         #[inline]
416         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
417                 Self {
418                         err: LightningError {
419                                 err: err.clone(),
420                                 action: msgs::ErrorAction::SendErrorMessage {
421                                         msg: msgs::ErrorMessage {
422                                                 channel_id,
423                                                 data: err
424                                         },
425                                 },
426                         },
427                         chan_id: None,
428                         shutdown_finish: None,
429                         channel_capacity: None,
430                 }
431         }
432         #[inline]
433         fn from_no_close(err: msgs::LightningError) -> Self {
434                 Self { err, chan_id: None, shutdown_finish: None, channel_capacity: None }
435         }
436         #[inline]
437         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 {
438                 Self {
439                         err: LightningError {
440                                 err: err.clone(),
441                                 action: msgs::ErrorAction::SendErrorMessage {
442                                         msg: msgs::ErrorMessage {
443                                                 channel_id,
444                                                 data: err
445                                         },
446                                 },
447                         },
448                         chan_id: Some((channel_id, user_channel_id)),
449                         shutdown_finish: Some((shutdown_res, channel_update)),
450                         channel_capacity: Some(channel_capacity)
451                 }
452         }
453         #[inline]
454         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
455                 Self {
456                         err: match err {
457                                 ChannelError::Warn(msg) =>  LightningError {
458                                         err: msg.clone(),
459                                         action: msgs::ErrorAction::SendWarningMessage {
460                                                 msg: msgs::WarningMessage {
461                                                         channel_id,
462                                                         data: msg
463                                                 },
464                                                 log_level: Level::Warn,
465                                         },
466                                 },
467                                 ChannelError::Ignore(msg) => LightningError {
468                                         err: msg,
469                                         action: msgs::ErrorAction::IgnoreError,
470                                 },
471                                 ChannelError::Close(msg) => LightningError {
472                                         err: msg.clone(),
473                                         action: msgs::ErrorAction::SendErrorMessage {
474                                                 msg: msgs::ErrorMessage {
475                                                         channel_id,
476                                                         data: msg
477                                                 },
478                                         },
479                                 },
480                         },
481                         chan_id: None,
482                         shutdown_finish: None,
483                         channel_capacity: None,
484                 }
485         }
486 }
487
488 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
489 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
490 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
491 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
492 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
493
494 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
495 /// be sent in the order they appear in the return value, however sometimes the order needs to be
496 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
497 /// they were originally sent). In those cases, this enum is also returned.
498 #[derive(Clone, PartialEq)]
499 pub(super) enum RAACommitmentOrder {
500         /// Send the CommitmentUpdate messages first
501         CommitmentFirst,
502         /// Send the RevokeAndACK message first
503         RevokeAndACKFirst,
504 }
505
506 /// Information about a payment which is currently being claimed.
507 struct ClaimingPayment {
508         amount_msat: u64,
509         payment_purpose: events::PaymentPurpose,
510         receiver_node_id: PublicKey,
511         htlcs: Vec<events::ClaimedHTLC>,
512         sender_intended_value: Option<u64>,
513 }
514 impl_writeable_tlv_based!(ClaimingPayment, {
515         (0, amount_msat, required),
516         (2, payment_purpose, required),
517         (4, receiver_node_id, required),
518         (5, htlcs, optional_vec),
519         (7, sender_intended_value, option),
520 });
521
522 struct ClaimablePayment {
523         purpose: events::PaymentPurpose,
524         onion_fields: Option<RecipientOnionFields>,
525         htlcs: Vec<ClaimableHTLC>,
526 }
527
528 /// Information about claimable or being-claimed payments
529 struct ClaimablePayments {
530         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
531         /// failed/claimed by the user.
532         ///
533         /// Note that, no consistency guarantees are made about the channels given here actually
534         /// existing anymore by the time you go to read them!
535         ///
536         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
537         /// we don't get a duplicate payment.
538         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
539
540         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
541         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
542         /// as an [`events::Event::PaymentClaimed`].
543         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
544 }
545
546 /// Events which we process internally but cannot be processed immediately at the generation site
547 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
548 /// running normally, and specifically must be processed before any other non-background
549 /// [`ChannelMonitorUpdate`]s are applied.
550 enum BackgroundEvent {
551         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
552         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
553         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
554         /// channel has been force-closed we do not need the counterparty node_id.
555         ///
556         /// Note that any such events are lost on shutdown, so in general they must be updates which
557         /// are regenerated on startup.
558         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelMonitorUpdate)),
559         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
560         /// channel to continue normal operation.
561         ///
562         /// In general this should be used rather than
563         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
564         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
565         /// error the other variant is acceptable.
566         ///
567         /// Note that any such events are lost on shutdown, so in general they must be updates which
568         /// are regenerated on startup.
569         MonitorUpdateRegeneratedOnStartup {
570                 counterparty_node_id: PublicKey,
571                 funding_txo: OutPoint,
572                 update: ChannelMonitorUpdate
573         },
574         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
575         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
576         /// on a channel.
577         MonitorUpdatesComplete {
578                 counterparty_node_id: PublicKey,
579                 channel_id: [u8; 32],
580         },
581 }
582
583 #[derive(Debug)]
584 pub(crate) enum MonitorUpdateCompletionAction {
585         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
586         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
587         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
588         /// event can be generated.
589         PaymentClaimed { payment_hash: PaymentHash },
590         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
591         /// operation of another channel.
592         ///
593         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
594         /// from completing a monitor update which removes the payment preimage until the inbound edge
595         /// completes a monitor update containing the payment preimage. In that case, after the inbound
596         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
597         /// outbound edge.
598         EmitEventAndFreeOtherChannel {
599                 event: events::Event,
600                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, RAAMonitorUpdateBlockingAction)>,
601         },
602 }
603
604 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
605         (0, PaymentClaimed) => { (0, payment_hash, required) },
606         (2, EmitEventAndFreeOtherChannel) => {
607                 (0, event, upgradable_required),
608                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
609                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
610                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
611                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
612                 // downgrades to prior versions.
613                 (1, downstream_counterparty_and_funding_outpoint, option),
614         },
615 );
616
617 #[derive(Clone, Debug, PartialEq, Eq)]
618 pub(crate) enum EventCompletionAction {
619         ReleaseRAAChannelMonitorUpdate {
620                 counterparty_node_id: PublicKey,
621                 channel_funding_outpoint: OutPoint,
622         },
623 }
624 impl_writeable_tlv_based_enum!(EventCompletionAction,
625         (0, ReleaseRAAChannelMonitorUpdate) => {
626                 (0, channel_funding_outpoint, required),
627                 (2, counterparty_node_id, required),
628         };
629 );
630
631 #[derive(Clone, PartialEq, Eq, Debug)]
632 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
633 /// the blocked action here. See enum variants for more info.
634 pub(crate) enum RAAMonitorUpdateBlockingAction {
635         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
636         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
637         /// durably to disk.
638         ForwardedPaymentInboundClaim {
639                 /// The upstream channel ID (i.e. the inbound edge).
640                 channel_id: [u8; 32],
641                 /// The HTLC ID on the inbound edge.
642                 htlc_id: u64,
643         },
644 }
645
646 impl RAAMonitorUpdateBlockingAction {
647         #[allow(unused)]
648         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
649                 Self::ForwardedPaymentInboundClaim {
650                         channel_id: prev_hop.outpoint.to_channel_id(),
651                         htlc_id: prev_hop.htlc_id,
652                 }
653         }
654 }
655
656 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
657         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
658 ;);
659
660
661 /// State we hold per-peer.
662 pub(super) struct PeerState<Signer: ChannelSigner> {
663         /// `channel_id` -> `Channel`.
664         ///
665         /// Holds all funded channels where the peer is the counterparty.
666         pub(super) channel_by_id: HashMap<[u8; 32], Channel<Signer>>,
667         /// `temporary_channel_id` -> `OutboundV1Channel`.
668         ///
669         /// Holds all outbound V1 channels where the peer is the counterparty. Once an outbound channel has
670         /// been assigned a `channel_id`, the entry in this map is removed and one is created in
671         /// `channel_by_id`.
672         pub(super) outbound_v1_channel_by_id: HashMap<[u8; 32], OutboundV1Channel<Signer>>,
673         /// `temporary_channel_id` -> `InboundV1Channel`.
674         ///
675         /// Holds all inbound V1 channels where the peer is the counterparty. Once an inbound channel has
676         /// been assigned a `channel_id`, the entry in this map is removed and one is created in
677         /// `channel_by_id`.
678         pub(super) inbound_v1_channel_by_id: HashMap<[u8; 32], InboundV1Channel<Signer>>,
679         /// `temporary_channel_id` -> `InboundChannelRequest`.
680         ///
681         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
682         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
683         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
684         /// the channel is rejected, then the entry is simply removed.
685         pub(super) inbound_channel_request_by_id: HashMap<[u8; 32], InboundChannelRequest>,
686         /// The latest `InitFeatures` we heard from the peer.
687         latest_features: InitFeatures,
688         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
689         /// for broadcast messages, where ordering isn't as strict).
690         pub(super) pending_msg_events: Vec<MessageSendEvent>,
691         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
692         /// user but which have not yet completed.
693         ///
694         /// Note that the channel may no longer exist. For example if the channel was closed but we
695         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
696         /// for a missing channel.
697         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
698         /// Map from a specific channel to some action(s) that should be taken when all pending
699         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
700         ///
701         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
702         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
703         /// channels with a peer this will just be one allocation and will amount to a linear list of
704         /// channels to walk, avoiding the whole hashing rigmarole.
705         ///
706         /// Note that the channel may no longer exist. For example, if a channel was closed but we
707         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
708         /// for a missing channel. While a malicious peer could construct a second channel with the
709         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
710         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
711         /// duplicates do not occur, so such channels should fail without a monitor update completing.
712         monitor_update_blocked_actions: BTreeMap<[u8; 32], Vec<MonitorUpdateCompletionAction>>,
713         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
714         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
715         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
716         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
717         actions_blocking_raa_monitor_updates: BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
718         /// The peer is currently connected (i.e. we've seen a
719         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
720         /// [`ChannelMessageHandler::peer_disconnected`].
721         is_connected: bool,
722 }
723
724 impl <Signer: ChannelSigner> PeerState<Signer> {
725         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
726         /// If true is passed for `require_disconnected`, the function will return false if we haven't
727         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
728         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
729                 if require_disconnected && self.is_connected {
730                         return false
731                 }
732                 self.channel_by_id.is_empty() && self.monitor_update_blocked_actions.is_empty()
733                         && self.in_flight_monitor_updates.is_empty()
734         }
735
736         // Returns a count of all channels we have with this peer, including unfunded channels.
737         fn total_channel_count(&self) -> usize {
738                 self.channel_by_id.len() +
739                         self.outbound_v1_channel_by_id.len() +
740                         self.inbound_v1_channel_by_id.len() +
741                         self.inbound_channel_request_by_id.len()
742         }
743
744         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
745         fn has_channel(&self, channel_id: &[u8; 32]) -> bool {
746                 self.channel_by_id.contains_key(channel_id) ||
747                         self.outbound_v1_channel_by_id.contains_key(channel_id) ||
748                         self.inbound_v1_channel_by_id.contains_key(channel_id) ||
749                         self.inbound_channel_request_by_id.contains_key(channel_id)
750         }
751 }
752
753 /// A not-yet-accepted inbound (from counterparty) channel. Once
754 /// accepted, the parameters will be used to construct a channel.
755 pub(super) struct InboundChannelRequest {
756         /// The original OpenChannel message.
757         pub open_channel_msg: msgs::OpenChannel,
758         /// The number of ticks remaining before the request expires.
759         pub ticks_remaining: i32,
760 }
761
762 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
763 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
764 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
765
766 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
767 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
768 ///
769 /// For users who don't want to bother doing their own payment preimage storage, we also store that
770 /// here.
771 ///
772 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
773 /// and instead encoding it in the payment secret.
774 struct PendingInboundPayment {
775         /// The payment secret that the sender must use for us to accept this payment
776         payment_secret: PaymentSecret,
777         /// Time at which this HTLC expires - blocks with a header time above this value will result in
778         /// this payment being removed.
779         expiry_time: u64,
780         /// Arbitrary identifier the user specifies (or not)
781         user_payment_id: u64,
782         // Other required attributes of the payment, optionally enforced:
783         payment_preimage: Option<PaymentPreimage>,
784         min_value_msat: Option<u64>,
785 }
786
787 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
788 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
789 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
790 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
791 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
792 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
793 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
794 /// of [`KeysManager`] and [`DefaultRouter`].
795 ///
796 /// This is not exported to bindings users as Arcs don't make sense in bindings
797 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
798         Arc<M>,
799         Arc<T>,
800         Arc<KeysManager>,
801         Arc<KeysManager>,
802         Arc<KeysManager>,
803         Arc<F>,
804         Arc<DefaultRouter<
805                 Arc<NetworkGraph<Arc<L>>>,
806                 Arc<L>,
807                 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
808                 ProbabilisticScoringFeeParameters,
809                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
810         >>,
811         Arc<L>
812 >;
813
814 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
815 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
816 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
817 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
818 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
819 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
820 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
821 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
822 /// of [`KeysManager`] and [`DefaultRouter`].
823 ///
824 /// This is not exported to bindings users as Arcs don't make sense in bindings
825 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
826         ChannelManager<
827                 &'a M,
828                 &'b T,
829                 &'c KeysManager,
830                 &'c KeysManager,
831                 &'c KeysManager,
832                 &'d F,
833                 &'e DefaultRouter<
834                         &'f NetworkGraph<&'g L>,
835                         &'g L,
836                         &'h Mutex<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
837                         ProbabilisticScoringFeeParameters,
838                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
839                 >,
840                 &'g L
841         >;
842
843 macro_rules! define_test_pub_trait { ($vis: vis) => {
844 /// A trivial trait which describes any [`ChannelManager`] used in testing.
845 $vis trait AChannelManager {
846         type Watch: chain::Watch<Self::Signer> + ?Sized;
847         type M: Deref<Target = Self::Watch>;
848         type Broadcaster: BroadcasterInterface + ?Sized;
849         type T: Deref<Target = Self::Broadcaster>;
850         type EntropySource: EntropySource + ?Sized;
851         type ES: Deref<Target = Self::EntropySource>;
852         type NodeSigner: NodeSigner + ?Sized;
853         type NS: Deref<Target = Self::NodeSigner>;
854         type Signer: WriteableEcdsaChannelSigner + Sized;
855         type SignerProvider: SignerProvider<Signer = Self::Signer> + ?Sized;
856         type SP: Deref<Target = Self::SignerProvider>;
857         type FeeEstimator: FeeEstimator + ?Sized;
858         type F: Deref<Target = Self::FeeEstimator>;
859         type Router: Router + ?Sized;
860         type R: Deref<Target = Self::Router>;
861         type Logger: Logger + ?Sized;
862         type L: Deref<Target = Self::Logger>;
863         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
864 }
865 } }
866 #[cfg(any(test, feature = "_test_utils"))]
867 define_test_pub_trait!(pub);
868 #[cfg(not(any(test, feature = "_test_utils")))]
869 define_test_pub_trait!(pub(crate));
870 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
871 for ChannelManager<M, T, ES, NS, SP, F, R, L>
872 where
873         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
874         T::Target: BroadcasterInterface,
875         ES::Target: EntropySource,
876         NS::Target: NodeSigner,
877         SP::Target: SignerProvider,
878         F::Target: FeeEstimator,
879         R::Target: Router,
880         L::Target: Logger,
881 {
882         type Watch = M::Target;
883         type M = M;
884         type Broadcaster = T::Target;
885         type T = T;
886         type EntropySource = ES::Target;
887         type ES = ES;
888         type NodeSigner = NS::Target;
889         type NS = NS;
890         type Signer = <SP::Target as SignerProvider>::Signer;
891         type SignerProvider = SP::Target;
892         type SP = SP;
893         type FeeEstimator = F::Target;
894         type F = F;
895         type Router = R::Target;
896         type R = R;
897         type Logger = L::Target;
898         type L = L;
899         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
900 }
901
902 /// Manager which keeps track of a number of channels and sends messages to the appropriate
903 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
904 ///
905 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
906 /// to individual Channels.
907 ///
908 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
909 /// all peers during write/read (though does not modify this instance, only the instance being
910 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
911 /// called [`funding_transaction_generated`] for outbound channels) being closed.
912 ///
913 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
914 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST write each monitor update out to disk before
915 /// returning from [`chain::Watch::watch_channel`]/[`update_channel`], with ChannelManagers, writing updates
916 /// happens out-of-band (and will prevent any other `ChannelManager` operations from occurring during
917 /// the serialization process). If the deserialized version is out-of-date compared to the
918 /// [`ChannelMonitor`] passed by reference to [`read`], those channels will be force-closed based on the
919 /// `ChannelMonitor` state and no funds will be lost (mod on-chain transaction fees).
920 ///
921 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
922 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
923 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
924 ///
925 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
926 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
927 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
928 /// offline for a full minute. In order to track this, you must call
929 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
930 ///
931 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
932 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
933 /// not have a channel with being unable to connect to us or open new channels with us if we have
934 /// many peers with unfunded channels.
935 ///
936 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
937 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
938 /// never limited. Please ensure you limit the count of such channels yourself.
939 ///
940 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
941 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
942 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
943 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
944 /// you're using lightning-net-tokio.
945 ///
946 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
947 /// [`funding_created`]: msgs::FundingCreated
948 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
949 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
950 /// [`update_channel`]: chain::Watch::update_channel
951 /// [`ChannelUpdate`]: msgs::ChannelUpdate
952 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
953 /// [`read`]: ReadableArgs::read
954 //
955 // Lock order:
956 // The tree structure below illustrates the lock order requirements for the different locks of the
957 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
958 // and should then be taken in the order of the lowest to the highest level in the tree.
959 // Note that locks on different branches shall not be taken at the same time, as doing so will
960 // create a new lock order for those specific locks in the order they were taken.
961 //
962 // Lock order tree:
963 //
964 // `total_consistency_lock`
965 //  |
966 //  |__`forward_htlcs`
967 //  |   |
968 //  |   |__`pending_intercepted_htlcs`
969 //  |
970 //  |__`per_peer_state`
971 //  |   |
972 //  |   |__`pending_inbound_payments`
973 //  |       |
974 //  |       |__`claimable_payments`
975 //  |       |
976 //  |       |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
977 //  |           |
978 //  |           |__`peer_state`
979 //  |               |
980 //  |               |__`id_to_peer`
981 //  |               |
982 //  |               |__`short_to_chan_info`
983 //  |               |
984 //  |               |__`outbound_scid_aliases`
985 //  |               |
986 //  |               |__`best_block`
987 //  |               |
988 //  |               |__`pending_events`
989 //  |                   |
990 //  |                   |__`pending_background_events`
991 //
992 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
993 where
994         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
995         T::Target: BroadcasterInterface,
996         ES::Target: EntropySource,
997         NS::Target: NodeSigner,
998         SP::Target: SignerProvider,
999         F::Target: FeeEstimator,
1000         R::Target: Router,
1001         L::Target: Logger,
1002 {
1003         default_configuration: UserConfig,
1004         genesis_hash: BlockHash,
1005         fee_estimator: LowerBoundedFeeEstimator<F>,
1006         chain_monitor: M,
1007         tx_broadcaster: T,
1008         #[allow(unused)]
1009         router: R,
1010
1011         /// See `ChannelManager` struct-level documentation for lock order requirements.
1012         #[cfg(test)]
1013         pub(super) best_block: RwLock<BestBlock>,
1014         #[cfg(not(test))]
1015         best_block: RwLock<BestBlock>,
1016         secp_ctx: Secp256k1<secp256k1::All>,
1017
1018         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1019         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1020         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1021         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1022         ///
1023         /// See `ChannelManager` struct-level documentation for lock order requirements.
1024         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1025
1026         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1027         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1028         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1029         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1030         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1031         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1032         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1033         /// after reloading from disk while replaying blocks against ChannelMonitors.
1034         ///
1035         /// See `PendingOutboundPayment` documentation for more info.
1036         ///
1037         /// See `ChannelManager` struct-level documentation for lock order requirements.
1038         pending_outbound_payments: OutboundPayments,
1039
1040         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1041         ///
1042         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1043         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1044         /// and via the classic SCID.
1045         ///
1046         /// Note that no consistency guarantees are made about the existence of a channel with the
1047         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1048         ///
1049         /// See `ChannelManager` struct-level documentation for lock order requirements.
1050         #[cfg(test)]
1051         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1052         #[cfg(not(test))]
1053         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1054         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1055         /// until the user tells us what we should do with them.
1056         ///
1057         /// See `ChannelManager` struct-level documentation for lock order requirements.
1058         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1059
1060         /// The sets of payments which are claimable or currently being claimed. See
1061         /// [`ClaimablePayments`]' individual field docs for more info.
1062         ///
1063         /// See `ChannelManager` struct-level documentation for lock order requirements.
1064         claimable_payments: Mutex<ClaimablePayments>,
1065
1066         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1067         /// and some closed channels which reached a usable state prior to being closed. This is used
1068         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1069         /// active channel list on load.
1070         ///
1071         /// See `ChannelManager` struct-level documentation for lock order requirements.
1072         outbound_scid_aliases: Mutex<HashSet<u64>>,
1073
1074         /// `channel_id` -> `counterparty_node_id`.
1075         ///
1076         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
1077         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
1078         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
1079         ///
1080         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1081         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1082         /// the handling of the events.
1083         ///
1084         /// Note that no consistency guarantees are made about the existence of a peer with the
1085         /// `counterparty_node_id` in our other maps.
1086         ///
1087         /// TODO:
1088         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1089         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1090         /// would break backwards compatability.
1091         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1092         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1093         /// required to access the channel with the `counterparty_node_id`.
1094         ///
1095         /// See `ChannelManager` struct-level documentation for lock order requirements.
1096         id_to_peer: Mutex<HashMap<[u8; 32], PublicKey>>,
1097
1098         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1099         ///
1100         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1101         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1102         /// confirmation depth.
1103         ///
1104         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1105         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1106         /// channel with the `channel_id` in our other maps.
1107         ///
1108         /// See `ChannelManager` struct-level documentation for lock order requirements.
1109         #[cfg(test)]
1110         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
1111         #[cfg(not(test))]
1112         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
1113
1114         our_network_pubkey: PublicKey,
1115
1116         inbound_payment_key: inbound_payment::ExpandedKey,
1117
1118         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1119         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1120         /// we encrypt the namespace identifier using these bytes.
1121         ///
1122         /// [fake scids]: crate::util::scid_utils::fake_scid
1123         fake_scid_rand_bytes: [u8; 32],
1124
1125         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1126         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1127         /// keeping additional state.
1128         probing_cookie_secret: [u8; 32],
1129
1130         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1131         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1132         /// very far in the past, and can only ever be up to two hours in the future.
1133         highest_seen_timestamp: AtomicUsize,
1134
1135         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1136         /// basis, as well as the peer's latest features.
1137         ///
1138         /// If we are connected to a peer we always at least have an entry here, even if no channels
1139         /// are currently open with that peer.
1140         ///
1141         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1142         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1143         /// channels.
1144         ///
1145         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1146         ///
1147         /// See `ChannelManager` struct-level documentation for lock order requirements.
1148         #[cfg(not(any(test, feature = "_test_utils")))]
1149         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
1150         #[cfg(any(test, feature = "_test_utils"))]
1151         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<<SP::Target as SignerProvider>::Signer>>>>,
1152
1153         /// The set of events which we need to give to the user to handle. In some cases an event may
1154         /// require some further action after the user handles it (currently only blocking a monitor
1155         /// update from being handed to the user to ensure the included changes to the channel state
1156         /// are handled by the user before they're persisted durably to disk). In that case, the second
1157         /// element in the tuple is set to `Some` with further details of the action.
1158         ///
1159         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1160         /// could be in the middle of being processed without the direct mutex held.
1161         ///
1162         /// See `ChannelManager` struct-level documentation for lock order requirements.
1163         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1164         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1165         pending_events_processor: AtomicBool,
1166
1167         /// If we are running during init (either directly during the deserialization method or in
1168         /// block connection methods which run after deserialization but before normal operation) we
1169         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1170         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1171         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1172         ///
1173         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1174         ///
1175         /// See `ChannelManager` struct-level documentation for lock order requirements.
1176         ///
1177         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1178         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1179         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1180         /// Essentially just when we're serializing ourselves out.
1181         /// Taken first everywhere where we are making changes before any other locks.
1182         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1183         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1184         /// Notifier the lock contains sends out a notification when the lock is released.
1185         total_consistency_lock: RwLock<()>,
1186
1187         background_events_processed_since_startup: AtomicBool,
1188
1189         persistence_notifier: Notifier,
1190
1191         entropy_source: ES,
1192         node_signer: NS,
1193         signer_provider: SP,
1194
1195         logger: L,
1196 }
1197
1198 /// Chain-related parameters used to construct a new `ChannelManager`.
1199 ///
1200 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1201 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1202 /// are not needed when deserializing a previously constructed `ChannelManager`.
1203 #[derive(Clone, Copy, PartialEq)]
1204 pub struct ChainParameters {
1205         /// The network for determining the `chain_hash` in Lightning messages.
1206         pub network: Network,
1207
1208         /// The hash and height of the latest block successfully connected.
1209         ///
1210         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1211         pub best_block: BestBlock,
1212 }
1213
1214 #[derive(Copy, Clone, PartialEq)]
1215 #[must_use]
1216 enum NotifyOption {
1217         DoPersist,
1218         SkipPersist,
1219 }
1220
1221 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1222 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1223 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1224 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1225 /// sending the aforementioned notification (since the lock being released indicates that the
1226 /// updates are ready for persistence).
1227 ///
1228 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1229 /// notify or not based on whether relevant changes have been made, providing a closure to
1230 /// `optionally_notify` which returns a `NotifyOption`.
1231 struct PersistenceNotifierGuard<'a, F: Fn() -> NotifyOption> {
1232         persistence_notifier: &'a Notifier,
1233         should_persist: F,
1234         // We hold onto this result so the lock doesn't get released immediately.
1235         _read_guard: RwLockReadGuard<'a, ()>,
1236 }
1237
1238 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1239         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl Fn() -> NotifyOption> {
1240                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1241                 let _ = cm.get_cm().process_background_events(); // We always persist
1242
1243                 PersistenceNotifierGuard {
1244                         persistence_notifier: &cm.get_cm().persistence_notifier,
1245                         should_persist: || -> NotifyOption { NotifyOption::DoPersist },
1246                         _read_guard: read_guard,
1247                 }
1248
1249         }
1250
1251         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1252         /// [`ChannelManager::process_background_events`] MUST be called first.
1253         fn optionally_notify<F: Fn() -> NotifyOption>(lock: &'a RwLock<()>, notifier: &'a Notifier, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1254                 let read_guard = lock.read().unwrap();
1255
1256                 PersistenceNotifierGuard {
1257                         persistence_notifier: notifier,
1258                         should_persist: persist_check,
1259                         _read_guard: read_guard,
1260                 }
1261         }
1262 }
1263
1264 impl<'a, F: Fn() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1265         fn drop(&mut self) {
1266                 if (self.should_persist)() == NotifyOption::DoPersist {
1267                         self.persistence_notifier.notify();
1268                 }
1269         }
1270 }
1271
1272 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1273 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1274 ///
1275 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1276 ///
1277 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1278 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1279 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1280 /// the maximum required amount in lnd as of March 2021.
1281 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1282
1283 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1284 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1285 ///
1286 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1287 ///
1288 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1289 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1290 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1291 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1292 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1293 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1294 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1295 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1296 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1297 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1298 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1299 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1300 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1301
1302 /// Minimum CLTV difference between the current block height and received inbound payments.
1303 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1304 /// this value.
1305 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1306 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1307 // a payment was being routed, so we add an extra block to be safe.
1308 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1309
1310 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1311 // ie that if the next-hop peer fails the HTLC within
1312 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1313 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1314 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1315 // LATENCY_GRACE_PERIOD_BLOCKS.
1316 #[deny(const_err)]
1317 #[allow(dead_code)]
1318 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;
1319
1320 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1321 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1322 #[deny(const_err)]
1323 #[allow(dead_code)]
1324 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1325
1326 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1327 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1328
1329 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the
1330 /// idempotency of payments by [`PaymentId`]. See
1331 /// [`OutboundPayments::remove_stale_resolved_payments`].
1332 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
1333
1334 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1335 /// until we mark the channel disabled and gossip the update.
1336 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1337
1338 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1339 /// we mark the channel enabled and gossip the update.
1340 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1341
1342 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1343 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1344 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1345 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1346
1347 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1348 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1349 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1350
1351 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1352 /// many peers we reject new (inbound) connections.
1353 const MAX_NO_CHANNEL_PEERS: usize = 250;
1354
1355 /// Information needed for constructing an invoice route hint for this channel.
1356 #[derive(Clone, Debug, PartialEq)]
1357 pub struct CounterpartyForwardingInfo {
1358         /// Base routing fee in millisatoshis.
1359         pub fee_base_msat: u32,
1360         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1361         pub fee_proportional_millionths: u32,
1362         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1363         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1364         /// `cltv_expiry_delta` for more details.
1365         pub cltv_expiry_delta: u16,
1366 }
1367
1368 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1369 /// to better separate parameters.
1370 #[derive(Clone, Debug, PartialEq)]
1371 pub struct ChannelCounterparty {
1372         /// The node_id of our counterparty
1373         pub node_id: PublicKey,
1374         /// The Features the channel counterparty provided upon last connection.
1375         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1376         /// many routing-relevant features are present in the init context.
1377         pub features: InitFeatures,
1378         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1379         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1380         /// claiming at least this value on chain.
1381         ///
1382         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1383         ///
1384         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1385         pub unspendable_punishment_reserve: u64,
1386         /// Information on the fees and requirements that the counterparty requires when forwarding
1387         /// payments to us through this channel.
1388         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1389         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1390         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1391         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1392         pub outbound_htlc_minimum_msat: Option<u64>,
1393         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1394         pub outbound_htlc_maximum_msat: Option<u64>,
1395 }
1396
1397 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1398 ///
1399 /// Balances of a channel are available through [`ChainMonitor::get_claimable_balances`] and
1400 /// [`ChannelMonitor::get_claimable_balances`], calculated with respect to the corresponding on-chain
1401 /// transactions.
1402 ///
1403 /// [`ChainMonitor::get_claimable_balances`]: crate::chain::chainmonitor::ChainMonitor::get_claimable_balances
1404 #[derive(Clone, Debug, PartialEq)]
1405 pub struct ChannelDetails {
1406         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1407         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1408         /// Note that this means this value is *not* persistent - it can change once during the
1409         /// lifetime of the channel.
1410         pub channel_id: [u8; 32],
1411         /// Parameters which apply to our counterparty. See individual fields for more information.
1412         pub counterparty: ChannelCounterparty,
1413         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1414         /// our counterparty already.
1415         ///
1416         /// Note that, if this has been set, `channel_id` will be equivalent to
1417         /// `funding_txo.unwrap().to_channel_id()`.
1418         pub funding_txo: Option<OutPoint>,
1419         /// The features which this channel operates with. See individual features for more info.
1420         ///
1421         /// `None` until negotiation completes and the channel type is finalized.
1422         pub channel_type: Option<ChannelTypeFeatures>,
1423         /// The position of the funding transaction in the chain. None if the funding transaction has
1424         /// not yet been confirmed and the channel fully opened.
1425         ///
1426         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1427         /// payments instead of this. See [`get_inbound_payment_scid`].
1428         ///
1429         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1430         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1431         ///
1432         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1433         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1434         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1435         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1436         /// [`confirmations_required`]: Self::confirmations_required
1437         pub short_channel_id: Option<u64>,
1438         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1439         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1440         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1441         /// `Some(0)`).
1442         ///
1443         /// This will be `None` as long as the channel is not available for routing outbound payments.
1444         ///
1445         /// [`short_channel_id`]: Self::short_channel_id
1446         /// [`confirmations_required`]: Self::confirmations_required
1447         pub outbound_scid_alias: Option<u64>,
1448         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1449         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1450         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1451         /// when they see a payment to be routed to us.
1452         ///
1453         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1454         /// previous values for inbound payment forwarding.
1455         ///
1456         /// [`short_channel_id`]: Self::short_channel_id
1457         pub inbound_scid_alias: Option<u64>,
1458         /// The value, in satoshis, of this channel as appears in the funding output
1459         pub channel_value_satoshis: u64,
1460         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1461         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1462         /// this value on chain.
1463         ///
1464         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1465         ///
1466         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1467         ///
1468         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1469         pub unspendable_punishment_reserve: Option<u64>,
1470         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1471         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1472         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1473         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1474         /// serialized with LDK versions prior to 0.0.113.
1475         ///
1476         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1477         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1478         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1479         pub user_channel_id: u128,
1480         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1481         /// which is applied to commitment and HTLC transactions.
1482         ///
1483         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1484         pub feerate_sat_per_1000_weight: Option<u32>,
1485         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1486         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1487         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1488         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1489         ///
1490         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1491         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1492         /// should be able to spend nearly this amount.
1493         pub outbound_capacity_msat: u64,
1494         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1495         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1496         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1497         /// to use a limit as close as possible to the HTLC limit we can currently send.
1498         ///
1499         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`] and
1500         /// [`ChannelDetails::outbound_capacity_msat`].
1501         pub next_outbound_htlc_limit_msat: u64,
1502         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1503         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1504         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1505         /// route which is valid.
1506         pub next_outbound_htlc_minimum_msat: u64,
1507         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1508         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1509         /// available for inclusion in new inbound HTLCs).
1510         /// Note that there are some corner cases not fully handled here, so the actual available
1511         /// inbound capacity may be slightly higher than this.
1512         ///
1513         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1514         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1515         /// However, our counterparty should be able to spend nearly this amount.
1516         pub inbound_capacity_msat: u64,
1517         /// The number of required confirmations on the funding transaction before the funding will be
1518         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1519         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1520         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1521         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1522         ///
1523         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1524         ///
1525         /// [`is_outbound`]: ChannelDetails::is_outbound
1526         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1527         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1528         pub confirmations_required: Option<u32>,
1529         /// The current number of confirmations on the funding transaction.
1530         ///
1531         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1532         pub confirmations: Option<u32>,
1533         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1534         /// until we can claim our funds after we force-close the channel. During this time our
1535         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1536         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1537         /// time to claim our non-HTLC-encumbered funds.
1538         ///
1539         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1540         pub force_close_spend_delay: Option<u16>,
1541         /// True if the channel was initiated (and thus funded) by us.
1542         pub is_outbound: bool,
1543         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1544         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1545         /// required confirmation count has been reached (and we were connected to the peer at some
1546         /// point after the funding transaction received enough confirmations). The required
1547         /// confirmation count is provided in [`confirmations_required`].
1548         ///
1549         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1550         pub is_channel_ready: bool,
1551         /// The stage of the channel's shutdown.
1552         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1553         pub channel_shutdown_state: Option<ChannelShutdownState>,
1554         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1555         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1556         ///
1557         /// This is a strict superset of `is_channel_ready`.
1558         pub is_usable: bool,
1559         /// True if this channel is (or will be) publicly-announced.
1560         pub is_public: bool,
1561         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1562         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1563         pub inbound_htlc_minimum_msat: Option<u64>,
1564         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1565         pub inbound_htlc_maximum_msat: Option<u64>,
1566         /// Set of configurable parameters that affect channel operation.
1567         ///
1568         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1569         pub config: Option<ChannelConfig>,
1570 }
1571
1572 impl ChannelDetails {
1573         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1574         /// This should be used for providing invoice hints or in any other context where our
1575         /// counterparty will forward a payment to us.
1576         ///
1577         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1578         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1579         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1580                 self.inbound_scid_alias.or(self.short_channel_id)
1581         }
1582
1583         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1584         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1585         /// we're sending or forwarding a payment outbound over this channel.
1586         ///
1587         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1588         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1589         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1590                 self.short_channel_id.or(self.outbound_scid_alias)
1591         }
1592
1593         fn from_channel_context<Signer: WriteableEcdsaChannelSigner, F: Deref>(
1594                 context: &ChannelContext<Signer>, best_block_height: u32, latest_features: InitFeatures,
1595                 fee_estimator: &LowerBoundedFeeEstimator<F>
1596         ) -> Self
1597         where F::Target: FeeEstimator
1598         {
1599                 let balance = context.get_available_balances(fee_estimator);
1600                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1601                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1602                 ChannelDetails {
1603                         channel_id: context.channel_id(),
1604                         counterparty: ChannelCounterparty {
1605                                 node_id: context.get_counterparty_node_id(),
1606                                 features: latest_features,
1607                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1608                                 forwarding_info: context.counterparty_forwarding_info(),
1609                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1610                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1611                                 // message (as they are always the first message from the counterparty).
1612                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1613                                 // default `0` value set by `Channel::new_outbound`.
1614                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1615                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1616                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1617                         },
1618                         funding_txo: context.get_funding_txo(),
1619                         // Note that accept_channel (or open_channel) is always the first message, so
1620                         // `have_received_message` indicates that type negotiation has completed.
1621                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1622                         short_channel_id: context.get_short_channel_id(),
1623                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1624                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1625                         channel_value_satoshis: context.get_value_satoshis(),
1626                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1627                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1628                         inbound_capacity_msat: balance.inbound_capacity_msat,
1629                         outbound_capacity_msat: balance.outbound_capacity_msat,
1630                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1631                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1632                         user_channel_id: context.get_user_id(),
1633                         confirmations_required: context.minimum_depth(),
1634                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1635                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1636                         is_outbound: context.is_outbound(),
1637                         is_channel_ready: context.is_usable(),
1638                         is_usable: context.is_live(),
1639                         is_public: context.should_announce(),
1640                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1641                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1642                         config: Some(context.config()),
1643                         channel_shutdown_state: Some(context.shutdown_state()),
1644                 }
1645         }
1646 }
1647
1648 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1649 /// Further information on the details of the channel shutdown.
1650 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1651 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1652 /// the channel will be removed shortly.
1653 /// Also note, that in normal operation, peers could disconnect at any of these states
1654 /// and require peer re-connection before making progress onto other states
1655 pub enum ChannelShutdownState {
1656         /// Channel has not sent or received a shutdown message.
1657         NotShuttingDown,
1658         /// Local node has sent a shutdown message for this channel.
1659         ShutdownInitiated,
1660         /// Shutdown message exchanges have concluded and the channels are in the midst of
1661         /// resolving all existing open HTLCs before closing can continue.
1662         ResolvingHTLCs,
1663         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1664         NegotiatingClosingFee,
1665         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1666         /// to drop the channel.
1667         ShutdownComplete,
1668 }
1669
1670 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1671 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1672 #[derive(Debug, PartialEq)]
1673 pub enum RecentPaymentDetails {
1674         /// When a payment is still being sent and awaiting successful delivery.
1675         Pending {
1676                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1677                 /// abandoned.
1678                 payment_hash: PaymentHash,
1679                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1680                 /// not just the amount currently inflight.
1681                 total_msat: u64,
1682         },
1683         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1684         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1685         /// payment is removed from tracking.
1686         Fulfilled {
1687                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1688                 /// made before LDK version 0.0.104.
1689                 payment_hash: Option<PaymentHash>,
1690         },
1691         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1692         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1693         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1694         Abandoned {
1695                 /// Hash of the payment that we have given up trying to send.
1696                 payment_hash: PaymentHash,
1697         },
1698 }
1699
1700 /// Route hints used in constructing invoices for [phantom node payents].
1701 ///
1702 /// [phantom node payments]: crate::sign::PhantomKeysManager
1703 #[derive(Clone)]
1704 pub struct PhantomRouteHints {
1705         /// The list of channels to be included in the invoice route hints.
1706         pub channels: Vec<ChannelDetails>,
1707         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1708         /// route hints.
1709         pub phantom_scid: u64,
1710         /// The pubkey of the real backing node that would ultimately receive the payment.
1711         pub real_node_pubkey: PublicKey,
1712 }
1713
1714 macro_rules! handle_error {
1715         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1716                 // In testing, ensure there are no deadlocks where the lock is already held upon
1717                 // entering the macro.
1718                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1719                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1720
1721                 match $internal {
1722                         Ok(msg) => Ok(msg),
1723                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish, channel_capacity }) => {
1724                                 let mut msg_events = Vec::with_capacity(2);
1725
1726                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1727                                         $self.finish_force_close_channel(shutdown_res);
1728                                         if let Some(update) = update_option {
1729                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1730                                                         msg: update
1731                                                 });
1732                                         }
1733                                         if let Some((channel_id, user_channel_id)) = chan_id {
1734                                                 $self.pending_events.lock().unwrap().push_back((events::Event::ChannelClosed {
1735                                                         channel_id, user_channel_id,
1736                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() },
1737                                                         counterparty_node_id: Some($counterparty_node_id),
1738                                                         channel_capacity_sats: channel_capacity,
1739                                                 }, None));
1740                                         }
1741                                 }
1742
1743                                 log_error!($self.logger, "{}", err.err);
1744                                 if let msgs::ErrorAction::IgnoreError = err.action {
1745                                 } else {
1746                                         msg_events.push(events::MessageSendEvent::HandleError {
1747                                                 node_id: $counterparty_node_id,
1748                                                 action: err.action.clone()
1749                                         });
1750                                 }
1751
1752                                 if !msg_events.is_empty() {
1753                                         let per_peer_state = $self.per_peer_state.read().unwrap();
1754                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
1755                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
1756                                                 peer_state.pending_msg_events.append(&mut msg_events);
1757                                         }
1758                                 }
1759
1760                                 // Return error in case higher-API need one
1761                                 Err(err)
1762                         },
1763                 }
1764         } };
1765         ($self: ident, $internal: expr) => {
1766                 match $internal {
1767                         Ok(res) => Ok(res),
1768                         Err((chan, msg_handle_err)) => {
1769                                 let counterparty_node_id = chan.get_counterparty_node_id();
1770                                 handle_error!($self, Err(msg_handle_err), counterparty_node_id).map_err(|err| (chan, err))
1771                         },
1772                 }
1773         };
1774 }
1775
1776 macro_rules! update_maps_on_chan_removal {
1777         ($self: expr, $channel_context: expr) => {{
1778                 $self.id_to_peer.lock().unwrap().remove(&$channel_context.channel_id());
1779                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1780                 if let Some(short_id) = $channel_context.get_short_channel_id() {
1781                         short_to_chan_info.remove(&short_id);
1782                 } else {
1783                         // If the channel was never confirmed on-chain prior to its closure, remove the
1784                         // outbound SCID alias we used for it from the collision-prevention set. While we
1785                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1786                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1787                         // opening a million channels with us which are closed before we ever reach the funding
1788                         // stage.
1789                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
1790                         debug_assert!(alias_removed);
1791                 }
1792                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
1793         }}
1794 }
1795
1796 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1797 macro_rules! convert_chan_err {
1798         ($self: ident, $err: expr, $channel: expr, $channel_id: expr) => {
1799                 match $err {
1800                         ChannelError::Warn(msg) => {
1801                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), $channel_id.clone()))
1802                         },
1803                         ChannelError::Ignore(msg) => {
1804                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $channel_id.clone()))
1805                         },
1806                         ChannelError::Close(msg) => {
1807                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", log_bytes!($channel_id[..]), msg);
1808                                 update_maps_on_chan_removal!($self, &$channel.context);
1809                                 let shutdown_res = $channel.context.force_shutdown(true);
1810                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.context.get_user_id(),
1811                                         shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok(), $channel.context.get_value_satoshis()))
1812                         },
1813                 }
1814         };
1815         ($self: ident, $err: expr, $channel_context: expr, $channel_id: expr, UNFUNDED) => {
1816                 match $err {
1817                         // We should only ever have `ChannelError::Close` when unfunded channels error.
1818                         // In any case, just close the channel.
1819                         ChannelError::Warn(msg) | ChannelError::Ignore(msg) | ChannelError::Close(msg) => {
1820                                 log_error!($self.logger, "Closing unfunded channel {} due to an error: {}", log_bytes!($channel_id[..]), msg);
1821                                 update_maps_on_chan_removal!($self, &$channel_context);
1822                                 let shutdown_res = $channel_context.force_shutdown(false);
1823                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel_context.get_user_id(),
1824                                         shutdown_res, None, $channel_context.get_value_satoshis()))
1825                         },
1826                 }
1827         }
1828 }
1829
1830 macro_rules! break_chan_entry {
1831         ($self: ident, $res: expr, $entry: expr) => {
1832                 match $res {
1833                         Ok(res) => res,
1834                         Err(e) => {
1835                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1836                                 if drop {
1837                                         $entry.remove_entry();
1838                                 }
1839                                 break Err(res);
1840                         }
1841                 }
1842         }
1843 }
1844
1845 macro_rules! try_v1_outbound_chan_entry {
1846         ($self: ident, $res: expr, $entry: expr) => {
1847                 match $res {
1848                         Ok(res) => res,
1849                         Err(e) => {
1850                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut().context, $entry.key(), UNFUNDED);
1851                                 if drop {
1852                                         $entry.remove_entry();
1853                                 }
1854                                 return Err(res);
1855                         }
1856                 }
1857         }
1858 }
1859
1860 macro_rules! try_chan_entry {
1861         ($self: ident, $res: expr, $entry: expr) => {
1862                 match $res {
1863                         Ok(res) => res,
1864                         Err(e) => {
1865                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1866                                 if drop {
1867                                         $entry.remove_entry();
1868                                 }
1869                                 return Err(res);
1870                         }
1871                 }
1872         }
1873 }
1874
1875 macro_rules! remove_channel {
1876         ($self: expr, $entry: expr) => {
1877                 {
1878                         let channel = $entry.remove_entry().1;
1879                         update_maps_on_chan_removal!($self, &channel.context);
1880                         channel
1881                 }
1882         }
1883 }
1884
1885 macro_rules! send_channel_ready {
1886         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1887                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1888                         node_id: $channel.context.get_counterparty_node_id(),
1889                         msg: $channel_ready_msg,
1890                 });
1891                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1892                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
1893                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1894                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1895                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1896                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1897                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
1898                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
1899                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
1900                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1901                 }
1902         }}
1903 }
1904
1905 macro_rules! emit_channel_pending_event {
1906         ($locked_events: expr, $channel: expr) => {
1907                 if $channel.context.should_emit_channel_pending_event() {
1908                         $locked_events.push_back((events::Event::ChannelPending {
1909                                 channel_id: $channel.context.channel_id(),
1910                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
1911                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
1912                                 user_channel_id: $channel.context.get_user_id(),
1913                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
1914                         }, None));
1915                         $channel.context.set_channel_pending_event_emitted();
1916                 }
1917         }
1918 }
1919
1920 macro_rules! emit_channel_ready_event {
1921         ($locked_events: expr, $channel: expr) => {
1922                 if $channel.context.should_emit_channel_ready_event() {
1923                         debug_assert!($channel.context.channel_pending_event_emitted());
1924                         $locked_events.push_back((events::Event::ChannelReady {
1925                                 channel_id: $channel.context.channel_id(),
1926                                 user_channel_id: $channel.context.get_user_id(),
1927                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
1928                                 channel_type: $channel.context.get_channel_type().clone(),
1929                         }, None));
1930                         $channel.context.set_channel_ready_event_emitted();
1931                 }
1932         }
1933 }
1934
1935 macro_rules! handle_monitor_update_completion {
1936         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
1937                 let mut updates = $chan.monitor_updating_restored(&$self.logger,
1938                         &$self.node_signer, $self.genesis_hash, &$self.default_configuration,
1939                         $self.best_block.read().unwrap().height());
1940                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
1941                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
1942                         // We only send a channel_update in the case where we are just now sending a
1943                         // channel_ready and the channel is in a usable state. We may re-send a
1944                         // channel_update later through the announcement_signatures process for public
1945                         // channels, but there's no reason not to just inform our counterparty of our fees
1946                         // now.
1947                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
1948                                 Some(events::MessageSendEvent::SendChannelUpdate {
1949                                         node_id: counterparty_node_id,
1950                                         msg,
1951                                 })
1952                         } else { None }
1953                 } else { None };
1954
1955                 let update_actions = $peer_state.monitor_update_blocked_actions
1956                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
1957
1958                 let htlc_forwards = $self.handle_channel_resumption(
1959                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
1960                         updates.commitment_update, updates.order, updates.accepted_htlcs,
1961                         updates.funding_broadcastable, updates.channel_ready,
1962                         updates.announcement_sigs);
1963                 if let Some(upd) = channel_update {
1964                         $peer_state.pending_msg_events.push(upd);
1965                 }
1966
1967                 let channel_id = $chan.context.channel_id();
1968                 core::mem::drop($peer_state_lock);
1969                 core::mem::drop($per_peer_state_lock);
1970
1971                 $self.handle_monitor_update_completion_actions(update_actions);
1972
1973                 if let Some(forwards) = htlc_forwards {
1974                         $self.forward_htlcs(&mut [forwards][..]);
1975                 }
1976                 $self.finalize_claims(updates.finalized_claimed_htlcs);
1977                 for failure in updates.failed_htlcs.drain(..) {
1978                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
1979                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
1980                 }
1981         } }
1982 }
1983
1984 macro_rules! handle_new_monitor_update {
1985         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, _internal, $remove: expr, $completed: expr) => { {
1986                 // update_maps_on_chan_removal needs to be able to take id_to_peer, so make sure we can in
1987                 // any case so that it won't deadlock.
1988                 debug_assert_ne!($self.id_to_peer.held_by_thread(), LockHeldState::HeldByThread);
1989                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
1990                 match $update_res {
1991                         ChannelMonitorUpdateStatus::InProgress => {
1992                                 log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
1993                                         log_bytes!($chan.context.channel_id()[..]));
1994                                 Ok(false)
1995                         },
1996                         ChannelMonitorUpdateStatus::PermanentFailure => {
1997                                 log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateStatus::PermanentFailure",
1998                                         log_bytes!($chan.context.channel_id()[..]));
1999                                 update_maps_on_chan_removal!($self, &$chan.context);
2000                                 let res = Err(MsgHandleErrInternal::from_finish_shutdown(
2001                                         "ChannelMonitor storage failure".to_owned(), $chan.context.channel_id(),
2002                                         $chan.context.get_user_id(), $chan.context.force_shutdown(false),
2003                                         $self.get_channel_update_for_broadcast(&$chan).ok(), $chan.context.get_value_satoshis()));
2004                                 $remove;
2005                                 res
2006                         },
2007                         ChannelMonitorUpdateStatus::Completed => {
2008                                 $completed;
2009                                 Ok(true)
2010                         },
2011                 }
2012         } };
2013         ($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) => {
2014                 handle_new_monitor_update!($self, $update_res, $peer_state_lock, $peer_state,
2015                         $per_peer_state_lock, $chan, _internal, $remove,
2016                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2017         };
2018         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr, INITIAL_MONITOR) => {
2019                 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())
2020         };
2021         ($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) => { {
2022                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2023                         .or_insert_with(Vec::new);
2024                 // During startup, we push monitor updates as background events through to here in
2025                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2026                 // filter for uniqueness here.
2027                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2028                         .unwrap_or_else(|| {
2029                                 in_flight_updates.push($update);
2030                                 in_flight_updates.len() - 1
2031                         });
2032                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2033                 handle_new_monitor_update!($self, update_res, $peer_state_lock, $peer_state,
2034                         $per_peer_state_lock, $chan, _internal, $remove,
2035                         {
2036                                 let _ = in_flight_updates.remove(idx);
2037                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2038                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2039                                 }
2040                         })
2041         } };
2042         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan_entry: expr) => {
2043                 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())
2044         }
2045 }
2046
2047 macro_rules! process_events_body {
2048         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2049                 let mut processed_all_events = false;
2050                 while !processed_all_events {
2051                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2052                                 return;
2053                         }
2054
2055                         let mut result = NotifyOption::SkipPersist;
2056
2057                         {
2058                                 // We'll acquire our total consistency lock so that we can be sure no other
2059                                 // persists happen while processing monitor events.
2060                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2061
2062                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2063                                 // ensure any startup-generated background events are handled first.
2064                                 if $self.process_background_events() == NotifyOption::DoPersist { result = NotifyOption::DoPersist; }
2065
2066                                 // TODO: This behavior should be documented. It's unintuitive that we query
2067                                 // ChannelMonitors when clearing other events.
2068                                 if $self.process_pending_monitor_events() {
2069                                         result = NotifyOption::DoPersist;
2070                                 }
2071                         }
2072
2073                         let pending_events = $self.pending_events.lock().unwrap().clone();
2074                         let num_events = pending_events.len();
2075                         if !pending_events.is_empty() {
2076                                 result = NotifyOption::DoPersist;
2077                         }
2078
2079                         let mut post_event_actions = Vec::new();
2080
2081                         for (event, action_opt) in pending_events {
2082                                 $event_to_handle = event;
2083                                 $handle_event;
2084                                 if let Some(action) = action_opt {
2085                                         post_event_actions.push(action);
2086                                 }
2087                         }
2088
2089                         {
2090                                 let mut pending_events = $self.pending_events.lock().unwrap();
2091                                 pending_events.drain(..num_events);
2092                                 processed_all_events = pending_events.is_empty();
2093                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2094                                 // updated here with the `pending_events` lock acquired.
2095                                 $self.pending_events_processor.store(false, Ordering::Release);
2096                         }
2097
2098                         if !post_event_actions.is_empty() {
2099                                 $self.handle_post_event_actions(post_event_actions);
2100                                 // If we had some actions, go around again as we may have more events now
2101                                 processed_all_events = false;
2102                         }
2103
2104                         if result == NotifyOption::DoPersist {
2105                                 $self.persistence_notifier.notify();
2106                         }
2107                 }
2108         }
2109 }
2110
2111 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>
2112 where
2113         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
2114         T::Target: BroadcasterInterface,
2115         ES::Target: EntropySource,
2116         NS::Target: NodeSigner,
2117         SP::Target: SignerProvider,
2118         F::Target: FeeEstimator,
2119         R::Target: Router,
2120         L::Target: Logger,
2121 {
2122         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2123         ///
2124         /// The current time or latest block header time can be provided as the `current_timestamp`.
2125         ///
2126         /// This is the main "logic hub" for all channel-related actions, and implements
2127         /// [`ChannelMessageHandler`].
2128         ///
2129         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2130         ///
2131         /// Users need to notify the new `ChannelManager` when a new block is connected or
2132         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2133         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2134         /// more details.
2135         ///
2136         /// [`block_connected`]: chain::Listen::block_connected
2137         /// [`block_disconnected`]: chain::Listen::block_disconnected
2138         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2139         pub fn new(
2140                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2141                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2142                 current_timestamp: u32,
2143         ) -> Self {
2144                 let mut secp_ctx = Secp256k1::new();
2145                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2146                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2147                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2148                 ChannelManager {
2149                         default_configuration: config.clone(),
2150                         genesis_hash: genesis_block(params.network).header.block_hash(),
2151                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2152                         chain_monitor,
2153                         tx_broadcaster,
2154                         router,
2155
2156                         best_block: RwLock::new(params.best_block),
2157
2158                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2159                         pending_inbound_payments: Mutex::new(HashMap::new()),
2160                         pending_outbound_payments: OutboundPayments::new(),
2161                         forward_htlcs: Mutex::new(HashMap::new()),
2162                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2163                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2164                         id_to_peer: Mutex::new(HashMap::new()),
2165                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2166
2167                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2168                         secp_ctx,
2169
2170                         inbound_payment_key: expanded_inbound_key,
2171                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2172
2173                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2174
2175                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2176
2177                         per_peer_state: FairRwLock::new(HashMap::new()),
2178
2179                         pending_events: Mutex::new(VecDeque::new()),
2180                         pending_events_processor: AtomicBool::new(false),
2181                         pending_background_events: Mutex::new(Vec::new()),
2182                         total_consistency_lock: RwLock::new(()),
2183                         background_events_processed_since_startup: AtomicBool::new(false),
2184                         persistence_notifier: Notifier::new(),
2185
2186                         entropy_source,
2187                         node_signer,
2188                         signer_provider,
2189
2190                         logger,
2191                 }
2192         }
2193
2194         /// Gets the current configuration applied to all new channels.
2195         pub fn get_current_default_configuration(&self) -> &UserConfig {
2196                 &self.default_configuration
2197         }
2198
2199         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2200                 let height = self.best_block.read().unwrap().height();
2201                 let mut outbound_scid_alias = 0;
2202                 let mut i = 0;
2203                 loop {
2204                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2205                                 outbound_scid_alias += 1;
2206                         } else {
2207                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2208                         }
2209                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2210                                 break;
2211                         }
2212                         i += 1;
2213                         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"); }
2214                 }
2215                 outbound_scid_alias
2216         }
2217
2218         /// Creates a new outbound channel to the given remote node and with the given value.
2219         ///
2220         /// `user_channel_id` will be provided back as in
2221         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2222         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2223         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2224         /// is simply copied to events and otherwise ignored.
2225         ///
2226         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2227         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2228         ///
2229         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2230         /// generate a shutdown scriptpubkey or destination script set by
2231         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2232         ///
2233         /// Note that we do not check if you are currently connected to the given peer. If no
2234         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2235         /// the channel eventually being silently forgotten (dropped on reload).
2236         ///
2237         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2238         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2239         /// [`ChannelDetails::channel_id`] until after
2240         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2241         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2242         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2243         ///
2244         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2245         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2246         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2247         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> {
2248                 if channel_value_satoshis < 1000 {
2249                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2250                 }
2251
2252                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2253                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2254                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2255
2256                 let per_peer_state = self.per_peer_state.read().unwrap();
2257
2258                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2259                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2260
2261                 let mut peer_state = peer_state_mutex.lock().unwrap();
2262                 let channel = {
2263                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2264                         let their_features = &peer_state.latest_features;
2265                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2266                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2267                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2268                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
2269                         {
2270                                 Ok(res) => res,
2271                                 Err(e) => {
2272                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2273                                         return Err(e);
2274                                 },
2275                         }
2276                 };
2277                 let res = channel.get_open_channel(self.genesis_hash.clone());
2278
2279                 let temporary_channel_id = channel.context.channel_id();
2280                 match peer_state.outbound_v1_channel_by_id.entry(temporary_channel_id) {
2281                         hash_map::Entry::Occupied(_) => {
2282                                 if cfg!(fuzzing) {
2283                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2284                                 } else {
2285                                         panic!("RNG is bad???");
2286                                 }
2287                         },
2288                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
2289                 }
2290
2291                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2292                         node_id: their_network_key,
2293                         msg: res,
2294                 });
2295                 Ok(temporary_channel_id)
2296         }
2297
2298         fn list_funded_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<<SP::Target as SignerProvider>::Signer>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2299                 // Allocate our best estimate of the number of channels we have in the `res`
2300                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2301                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2302                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2303                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2304                 // the same channel.
2305                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2306                 {
2307                         let best_block_height = self.best_block.read().unwrap().height();
2308                         let per_peer_state = self.per_peer_state.read().unwrap();
2309                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2310                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2311                                 let peer_state = &mut *peer_state_lock;
2312                                 // Only `Channels` in the channel_by_id map can be considered funded.
2313                                 for (_channel_id, channel) in peer_state.channel_by_id.iter().filter(f) {
2314                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2315                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2316                                         res.push(details);
2317                                 }
2318                         }
2319                 }
2320                 res
2321         }
2322
2323         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2324         /// more information.
2325         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2326                 // Allocate our best estimate of the number of channels we have in the `res`
2327                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2328                 // a scid or a scid alias, and the `id_to_peer` shouldn't be used outside
2329                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2330                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2331                 // the same channel.
2332                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2333                 {
2334                         let best_block_height = self.best_block.read().unwrap().height();
2335                         let per_peer_state = self.per_peer_state.read().unwrap();
2336                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2337                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2338                                 let peer_state = &mut *peer_state_lock;
2339                                 for (_channel_id, channel) in peer_state.channel_by_id.iter() {
2340                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2341                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2342                                         res.push(details);
2343                                 }
2344                                 for (_channel_id, channel) in peer_state.inbound_v1_channel_by_id.iter() {
2345                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2346                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2347                                         res.push(details);
2348                                 }
2349                                 for (_channel_id, channel) in peer_state.outbound_v1_channel_by_id.iter() {
2350                                         let details = ChannelDetails::from_channel_context(&channel.context, best_block_height,
2351                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2352                                         res.push(details);
2353                                 }
2354                         }
2355                 }
2356                 res
2357         }
2358
2359         /// Gets the list of usable channels, in random order. Useful as an argument to
2360         /// [`Router::find_route`] to ensure non-announced channels are used.
2361         ///
2362         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2363         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2364         /// are.
2365         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2366                 // Note we use is_live here instead of usable which leads to somewhat confused
2367                 // internal/external nomenclature, but that's ok cause that's probably what the user
2368                 // really wanted anyway.
2369                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2370         }
2371
2372         /// Gets the list of channels we have with a given counterparty, in random order.
2373         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2374                 let best_block_height = self.best_block.read().unwrap().height();
2375                 let per_peer_state = self.per_peer_state.read().unwrap();
2376
2377                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2378                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2379                         let peer_state = &mut *peer_state_lock;
2380                         let features = &peer_state.latest_features;
2381                         let chan_context_to_details = |context| {
2382                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2383                         };
2384                         return peer_state.channel_by_id
2385                                 .iter()
2386                                 .map(|(_, channel)| &channel.context)
2387                                 .chain(peer_state.outbound_v1_channel_by_id.iter().map(|(_, channel)| &channel.context))
2388                                 .chain(peer_state.inbound_v1_channel_by_id.iter().map(|(_, channel)| &channel.context))
2389                                 .map(chan_context_to_details)
2390                                 .collect();
2391                 }
2392                 vec![]
2393         }
2394
2395         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2396         /// successful path, or have unresolved HTLCs.
2397         ///
2398         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2399         /// result of a crash. If such a payment exists, is not listed here, and an
2400         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2401         ///
2402         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2403         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2404                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2405                         .filter_map(|(_, pending_outbound_payment)| match pending_outbound_payment {
2406                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2407                                         Some(RecentPaymentDetails::Pending {
2408                                                 payment_hash: *payment_hash,
2409                                                 total_msat: *total_msat,
2410                                         })
2411                                 },
2412                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2413                                         Some(RecentPaymentDetails::Abandoned { payment_hash: *payment_hash })
2414                                 },
2415                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2416                                         Some(RecentPaymentDetails::Fulfilled { payment_hash: *payment_hash })
2417                                 },
2418                                 PendingOutboundPayment::Legacy { .. } => None
2419                         })
2420                         .collect()
2421         }
2422
2423         /// Helper function that issues the channel close events
2424         fn issue_channel_close_events(&self, context: &ChannelContext<<SP::Target as SignerProvider>::Signer>, closure_reason: ClosureReason) {
2425                 let mut pending_events_lock = self.pending_events.lock().unwrap();
2426                 match context.unbroadcasted_funding() {
2427                         Some(transaction) => {
2428                                 pending_events_lock.push_back((events::Event::DiscardFunding {
2429                                         channel_id: context.channel_id(), transaction
2430                                 }, None));
2431                         },
2432                         None => {},
2433                 }
2434                 pending_events_lock.push_back((events::Event::ChannelClosed {
2435                         channel_id: context.channel_id(),
2436                         user_channel_id: context.get_user_id(),
2437                         reason: closure_reason,
2438                         counterparty_node_id: Some(context.get_counterparty_node_id()),
2439                         channel_capacity_sats: Some(context.get_value_satoshis()),
2440                 }, None));
2441         }
2442
2443         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> {
2444                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2445
2446                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
2447                 let result: Result<(), _> = loop {
2448                         {
2449                                 let per_peer_state = self.per_peer_state.read().unwrap();
2450
2451                                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2452                                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2453
2454                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2455                                 let peer_state = &mut *peer_state_lock;
2456
2457                                 match peer_state.channel_by_id.entry(channel_id.clone()) {
2458                                         hash_map::Entry::Occupied(mut chan_entry) => {
2459                                                 let funding_txo_opt = chan_entry.get().context.get_funding_txo();
2460                                                 let their_features = &peer_state.latest_features;
2461                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) = chan_entry.get_mut()
2462                                                         .get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2463                                                 failed_htlcs = htlcs;
2464
2465                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2466                                                 // here as we don't need the monitor update to complete until we send a
2467                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2468                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2469                                                         node_id: *counterparty_node_id,
2470                                                         msg: shutdown_msg,
2471                                                 });
2472
2473                                                 // Update the monitor with the shutdown script if necessary.
2474                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2475                                                         break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2476                                                                 peer_state_lock, peer_state, per_peer_state, chan_entry).map(|_| ());
2477                                                 }
2478
2479                                                 if chan_entry.get().is_shutdown() {
2480                                                         let channel = remove_channel!(self, chan_entry);
2481                                                         if let Ok(channel_update) = self.get_channel_update_for_broadcast(&channel) {
2482                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2483                                                                         msg: channel_update
2484                                                                 });
2485                                                         }
2486                                                         self.issue_channel_close_events(&channel.context, ClosureReason::HolderForceClosed);
2487                                                 }
2488                                                 break Ok(());
2489                                         },
2490                                         hash_map::Entry::Vacant(_) => (),
2491                                 }
2492                         }
2493                         // If we reach this point, it means that the channel_id either refers to an unfunded channel or
2494                         // it does not exist for this peer. Either way, we can attempt to force-close it.
2495                         //
2496                         // An appropriate error will be returned for non-existence of the channel if that's the case.
2497                         return self.force_close_channel_with_peer(&channel_id, counterparty_node_id, None, false).map(|_| ())
2498                         // TODO(dunxen): This is still not ideal as we're doing some extra lookups.
2499                         // Fix this with https://github.com/lightningdevkit/rust-lightning/issues/2422
2500                 };
2501
2502                 for htlc_source in failed_htlcs.drain(..) {
2503                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2504                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2505                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2506                 }
2507
2508                 let _ = handle_error!(self, result, *counterparty_node_id);
2509                 Ok(())
2510         }
2511
2512         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2513         /// will be accepted on the given channel, and after additional timeout/the closing of all
2514         /// pending HTLCs, the channel will be closed on chain.
2515         ///
2516         ///  * If we are the channel initiator, we will pay between our [`Background`] and
2517         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2518         ///    estimate.
2519         ///  * If our counterparty is the channel initiator, we will require a channel closing
2520         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
2521         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2522         ///    counterparty to pay as much fee as they'd like, however.
2523         ///
2524         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2525         ///
2526         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2527         /// generate a shutdown scriptpubkey or destination script set by
2528         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2529         /// channel.
2530         ///
2531         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2532         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2533         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2534         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2535         pub fn close_channel(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2536                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2537         }
2538
2539         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2540         /// will be accepted on the given channel, and after additional timeout/the closing of all
2541         /// pending HTLCs, the channel will be closed on chain.
2542         ///
2543         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2544         /// the channel being closed or not:
2545         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2546         ///    transaction. The upper-bound is set by
2547         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2548         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2549         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2550         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2551         ///    will appear on a force-closure transaction, whichever is lower).
2552         ///
2553         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2554         /// Will fail if a shutdown script has already been set for this channel by
2555         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2556         /// also be compatible with our and the counterparty's features.
2557         ///
2558         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2559         ///
2560         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2561         /// generate a shutdown scriptpubkey or destination script set by
2562         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2563         /// channel.
2564         ///
2565         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2566         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2567         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2568         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2569         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> {
2570                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2571         }
2572
2573         #[inline]
2574         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
2575                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
2576                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
2577                 for htlc_source in failed_htlcs.drain(..) {
2578                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2579                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2580                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2581                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2582                 }
2583                 if let Some((_, funding_txo, monitor_update)) = monitor_update_option {
2584                         // There isn't anything we can do if we get an update failure - we're already
2585                         // force-closing. The monitor update on the required in-memory copy should broadcast
2586                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2587                         // ignore the result here.
2588                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2589                 }
2590         }
2591
2592         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2593         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2594         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2595         -> Result<PublicKey, APIError> {
2596                 let per_peer_state = self.per_peer_state.read().unwrap();
2597                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2598                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2599                 let (update_opt, counterparty_node_id) = {
2600                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2601                         let peer_state = &mut *peer_state_lock;
2602                         let closure_reason = if let Some(peer_msg) = peer_msg {
2603                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2604                         } else {
2605                                 ClosureReason::HolderForceClosed
2606                         };
2607                         if let hash_map::Entry::Occupied(chan) = peer_state.channel_by_id.entry(channel_id.clone()) {
2608                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2609                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2610                                 let mut chan = remove_channel!(self, chan);
2611                                 self.finish_force_close_channel(chan.context.force_shutdown(broadcast));
2612                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2613                         } else if let hash_map::Entry::Occupied(chan) = peer_state.outbound_v1_channel_by_id.entry(channel_id.clone()) {
2614                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2615                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2616                                 let mut chan = remove_channel!(self, chan);
2617                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
2618                                 // Unfunded channel has no update
2619                                 (None, chan.context.get_counterparty_node_id())
2620                         } else if let hash_map::Entry::Occupied(chan) = peer_state.inbound_v1_channel_by_id.entry(channel_id.clone()) {
2621                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2622                                 self.issue_channel_close_events(&chan.get().context, closure_reason);
2623                                 let mut chan = remove_channel!(self, chan);
2624                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
2625                                 // Unfunded channel has no update
2626                                 (None, chan.context.get_counterparty_node_id())
2627                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2628                                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
2629                                 // N.B. that we don't send any channel close event here: we
2630                                 // don't have a user_channel_id, and we never sent any opening
2631                                 // events anyway.
2632                                 (None, *peer_node_id)
2633                         } else {
2634                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(*channel_id), peer_node_id) });
2635                         }
2636                 };
2637                 if let Some(update) = update_opt {
2638                         let mut peer_state = peer_state_mutex.lock().unwrap();
2639                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2640                                 msg: update
2641                         });
2642                 }
2643
2644                 Ok(counterparty_node_id)
2645         }
2646
2647         fn force_close_sending_error(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2648                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2649                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2650                         Ok(counterparty_node_id) => {
2651                                 let per_peer_state = self.per_peer_state.read().unwrap();
2652                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2653                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2654                                         peer_state.pending_msg_events.push(
2655                                                 events::MessageSendEvent::HandleError {
2656                                                         node_id: counterparty_node_id,
2657                                                         action: msgs::ErrorAction::SendErrorMessage {
2658                                                                 msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
2659                                                         },
2660                                                 }
2661                                         );
2662                                 }
2663                                 Ok(())
2664                         },
2665                         Err(e) => Err(e)
2666                 }
2667         }
2668
2669         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2670         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2671         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2672         /// channel.
2673         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2674         -> Result<(), APIError> {
2675                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
2676         }
2677
2678         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2679         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2680         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2681         ///
2682         /// You can always get the latest local transaction(s) to broadcast from
2683         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
2684         pub fn force_close_without_broadcasting_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
2685         -> Result<(), APIError> {
2686                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
2687         }
2688
2689         /// Force close all channels, immediately broadcasting the latest local commitment transaction
2690         /// for each to the chain and rejecting new HTLCs on each.
2691         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
2692                 for chan in self.list_channels() {
2693                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
2694                 }
2695         }
2696
2697         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2698         /// local transaction(s).
2699         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
2700                 for chan in self.list_channels() {
2701                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
2702                 }
2703         }
2704
2705         fn construct_fwd_pending_htlc_info(
2706                 &self, msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
2707                 new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
2708                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
2709         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2710                 debug_assert!(next_packet_pubkey_opt.is_some());
2711                 let outgoing_packet = msgs::OnionPacket {
2712                         version: 0,
2713                         public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
2714                         hop_data: new_packet_bytes,
2715                         hmac: hop_hmac,
2716                 };
2717
2718                 let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
2719                         msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
2720                                 (short_channel_id, amt_to_forward, outgoing_cltv_value),
2721                         msgs::InboundOnionPayload::Receive { .. } =>
2722                                 return Err(InboundOnionErr {
2723                                         msg: "Final Node OnionHopData provided for us as an intermediary node",
2724                                         err_code: 0x4000 | 22,
2725                                         err_data: Vec::new(),
2726                                 }),
2727                 };
2728
2729                 Ok(PendingHTLCInfo {
2730                         routing: PendingHTLCRouting::Forward {
2731                                 onion_packet: outgoing_packet,
2732                                 short_channel_id,
2733                         },
2734                         payment_hash: msg.payment_hash,
2735                         incoming_shared_secret: shared_secret,
2736                         incoming_amt_msat: Some(msg.amount_msat),
2737                         outgoing_amt_msat: amt_to_forward,
2738                         outgoing_cltv_value,
2739                         skimmed_fee_msat: None,
2740                 })
2741         }
2742
2743         fn construct_recv_pending_htlc_info(
2744                 &self, hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
2745                 amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
2746                 counterparty_skimmed_fee_msat: Option<u64>,
2747         ) -> Result<PendingHTLCInfo, InboundOnionErr> {
2748                 let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
2749                         msgs::InboundOnionPayload::Receive {
2750                                 payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
2751                         } =>
2752                                 (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
2753                         _ =>
2754                                 return Err(InboundOnionErr {
2755                                         err_code: 0x4000|22,
2756                                         err_data: Vec::new(),
2757                                         msg: "Got non final data with an HMAC of 0",
2758                                 }),
2759                 };
2760                 // final_incorrect_cltv_expiry
2761                 if outgoing_cltv_value > cltv_expiry {
2762                         return Err(InboundOnionErr {
2763                                 msg: "Upstream node set CLTV to less than the CLTV set by the sender",
2764                                 err_code: 18,
2765                                 err_data: cltv_expiry.to_be_bytes().to_vec()
2766                         })
2767                 }
2768                 // final_expiry_too_soon
2769                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
2770                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
2771                 //
2772                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
2773                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
2774                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
2775                 let current_height: u32 = self.best_block.read().unwrap().height();
2776                 if (outgoing_cltv_value as u64) <= current_height as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
2777                         let mut err_data = Vec::with_capacity(12);
2778                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
2779                         err_data.extend_from_slice(&current_height.to_be_bytes());
2780                         return Err(InboundOnionErr {
2781                                 err_code: 0x4000 | 15, err_data,
2782                                 msg: "The final CLTV expiry is too soon to handle",
2783                         });
2784                 }
2785                 if (!allow_underpay && onion_amt_msat > amt_msat) ||
2786                         (allow_underpay && onion_amt_msat >
2787                          amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
2788                 {
2789                         return Err(InboundOnionErr {
2790                                 err_code: 19,
2791                                 err_data: amt_msat.to_be_bytes().to_vec(),
2792                                 msg: "Upstream node sent less than we were supposed to receive in payment",
2793                         });
2794                 }
2795
2796                 let routing = if let Some(payment_preimage) = keysend_preimage {
2797                         // We need to check that the sender knows the keysend preimage before processing this
2798                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
2799                         // could discover the final destination of X, by probing the adjacent nodes on the route
2800                         // with a keysend payment of identical payment hash to X and observing the processing
2801                         // time discrepancies due to a hash collision with X.
2802                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2803                         if hashed_preimage != payment_hash {
2804                                 return Err(InboundOnionErr {
2805                                         err_code: 0x4000|22,
2806                                         err_data: Vec::new(),
2807                                         msg: "Payment preimage didn't match payment hash",
2808                                 });
2809                         }
2810                         if !self.default_configuration.accept_mpp_keysend && payment_data.is_some() {
2811                                 return Err(InboundOnionErr {
2812                                         err_code: 0x4000|22,
2813                                         err_data: Vec::new(),
2814                                         msg: "We don't support MPP keysend payments",
2815                                 });
2816                         }
2817                         PendingHTLCRouting::ReceiveKeysend {
2818                                 payment_data,
2819                                 payment_preimage,
2820                                 payment_metadata,
2821                                 incoming_cltv_expiry: outgoing_cltv_value,
2822                                 custom_tlvs,
2823                         }
2824                 } else if let Some(data) = payment_data {
2825                         PendingHTLCRouting::Receive {
2826                                 payment_data: data,
2827                                 payment_metadata,
2828                                 incoming_cltv_expiry: outgoing_cltv_value,
2829                                 phantom_shared_secret,
2830                                 custom_tlvs,
2831                         }
2832                 } else {
2833                         return Err(InboundOnionErr {
2834                                 err_code: 0x4000|0x2000|3,
2835                                 err_data: Vec::new(),
2836                                 msg: "We require payment_secrets",
2837                         });
2838                 };
2839                 Ok(PendingHTLCInfo {
2840                         routing,
2841                         payment_hash,
2842                         incoming_shared_secret: shared_secret,
2843                         incoming_amt_msat: Some(amt_msat),
2844                         outgoing_amt_msat: onion_amt_msat,
2845                         outgoing_cltv_value,
2846                         skimmed_fee_msat: counterparty_skimmed_fee_msat,
2847                 })
2848         }
2849
2850         fn decode_update_add_htlc_onion(
2851                 &self, msg: &msgs::UpdateAddHTLC
2852         ) -> Result<(onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg> {
2853                 macro_rules! return_malformed_err {
2854                         ($msg: expr, $err_code: expr) => {
2855                                 {
2856                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2857                                         return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
2858                                                 channel_id: msg.channel_id,
2859                                                 htlc_id: msg.htlc_id,
2860                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
2861                                                 failure_code: $err_code,
2862                                         }));
2863                                 }
2864                         }
2865                 }
2866
2867                 if let Err(_) = msg.onion_routing_packet.public_key {
2868                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
2869                 }
2870
2871                 let shared_secret = self.node_signer.ecdh(
2872                         Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
2873                 ).unwrap().secret_bytes();
2874
2875                 if msg.onion_routing_packet.version != 0 {
2876                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
2877                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
2878                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
2879                         //receiving node would have to brute force to figure out which version was put in the
2880                         //packet by the node that send us the message, in the case of hashing the hop_data, the
2881                         //node knows the HMAC matched, so they already know what is there...
2882                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
2883                 }
2884                 macro_rules! return_err {
2885                         ($msg: expr, $err_code: expr, $data: expr) => {
2886                                 {
2887                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2888                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2889                                                 channel_id: msg.channel_id,
2890                                                 htlc_id: msg.htlc_id,
2891                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
2892                                                         .get_encrypted_failure_packet(&shared_secret, &None),
2893                                         }));
2894                                 }
2895                         }
2896                 }
2897
2898                 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) {
2899                         Ok(res) => res,
2900                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2901                                 return_malformed_err!(err_msg, err_code);
2902                         },
2903                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2904                                 return_err!(err_msg, err_code, &[0; 0]);
2905                         },
2906                 };
2907                 let (outgoing_scid, outgoing_amt_msat, outgoing_cltv_value, next_packet_pk_opt) = match next_hop {
2908                         onion_utils::Hop::Forward {
2909                                 next_hop_data: msgs::InboundOnionPayload::Forward {
2910                                         short_channel_id, amt_to_forward, outgoing_cltv_value
2911                                 }, ..
2912                         } => {
2913                                 let next_pk = onion_utils::next_hop_packet_pubkey(&self.secp_ctx,
2914                                         msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
2915                                 (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(next_pk))
2916                         },
2917                         // We'll do receive checks in [`Self::construct_pending_htlc_info`] so we have access to the
2918                         // inbound channel's state.
2919                         onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
2920                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } => {
2921                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
2922                         }
2923                 };
2924
2925                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
2926                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
2927                 if let Some((err, mut code, chan_update)) = loop {
2928                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
2929                         let forwarding_chan_info_opt = match id_option {
2930                                 None => { // unknown_next_peer
2931                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2932                                         // phantom or an intercept.
2933                                         if (self.default_configuration.accept_intercept_htlcs &&
2934                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)) ||
2935                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)
2936                                         {
2937                                                 None
2938                                         } else {
2939                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2940                                         }
2941                                 },
2942                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
2943                         };
2944                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
2945                                 let per_peer_state = self.per_peer_state.read().unwrap();
2946                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
2947                                 if peer_state_mutex_opt.is_none() {
2948                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2949                                 }
2950                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
2951                                 let peer_state = &mut *peer_state_lock;
2952                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id) {
2953                                         None => {
2954                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
2955                                                 // have no consistency guarantees.
2956                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2957                                         },
2958                                         Some(chan) => chan
2959                                 };
2960                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2961                                         // Note that the behavior here should be identical to the above block - we
2962                                         // should NOT reveal the existence or non-existence of a private channel if
2963                                         // we don't allow forwards outbound over them.
2964                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2965                                 }
2966                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
2967                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
2968                                         // "refuse to forward unless the SCID alias was used", so we pretend
2969                                         // we don't have the channel here.
2970                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
2971                                 }
2972                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
2973
2974                                 // Note that we could technically not return an error yet here and just hope
2975                                 // that the connection is reestablished or monitor updated by the time we get
2976                                 // around to doing the actual forward, but better to fail early if we can and
2977                                 // hopefully an attacker trying to path-trace payments cannot make this occur
2978                                 // on a small/per-node/per-channel scale.
2979                                 if !chan.context.is_live() { // channel_disabled
2980                                         // If the channel_update we're going to return is disabled (i.e. the
2981                                         // peer has been disabled for some time), return `channel_disabled`,
2982                                         // otherwise return `temporary_channel_failure`.
2983                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
2984                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
2985                                         } else {
2986                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
2987                                         }
2988                                 }
2989                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
2990                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
2991                                 }
2992                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
2993                                         break Some((err, code, chan_update_opt));
2994                                 }
2995                                 chan_update_opt
2996                         } else {
2997                                 if (msg.cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
2998                                         // We really should set `incorrect_cltv_expiry` here but as we're not
2999                                         // forwarding over a real channel we can't generate a channel_update
3000                                         // for it. Instead we just return a generic temporary_node_failure.
3001                                         break Some((
3002                                                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
3003                                                         0x2000 | 2, None,
3004                                         ));
3005                                 }
3006                                 None
3007                         };
3008
3009                         let cur_height = self.best_block.read().unwrap().height() + 1;
3010                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
3011                         // but we want to be robust wrt to counterparty packet sanitization (see
3012                         // HTLC_FAIL_BACK_BUFFER rationale).
3013                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
3014                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
3015                         }
3016                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
3017                                 break Some(("CLTV expiry is too far in the future", 21, None));
3018                         }
3019                         // If the HTLC expires ~now, don't bother trying to forward it to our
3020                         // counterparty. They should fail it anyway, but we don't want to bother with
3021                         // the round-trips or risk them deciding they definitely want the HTLC and
3022                         // force-closing to ensure they get it if we're offline.
3023                         // We previously had a much more aggressive check here which tried to ensure
3024                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
3025                         // but there is no need to do that, and since we're a bit conservative with our
3026                         // risk threshold it just results in failing to forward payments.
3027                         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
3028                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
3029                         }
3030
3031                         break None;
3032                 }
3033                 {
3034                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3035                         if let Some(chan_update) = chan_update {
3036                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3037                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3038                                 }
3039                                 else if code == 0x1000 | 13 {
3040                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3041                                 }
3042                                 else if code == 0x1000 | 20 {
3043                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3044                                         0u16.write(&mut res).expect("Writes cannot fail");
3045                                 }
3046                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3047                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3048                                 chan_update.write(&mut res).expect("Writes cannot fail");
3049                         } else if code & 0x1000 == 0x1000 {
3050                                 // If we're trying to return an error that requires a `channel_update` but
3051                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3052                                 // generate an update), just use the generic "temporary_node_failure"
3053                                 // instead.
3054                                 code = 0x2000 | 2;
3055                         }
3056                         return_err!(err, code, &res.0[..]);
3057                 }
3058                 Ok((next_hop, shared_secret, next_packet_pk_opt))
3059         }
3060
3061         fn construct_pending_htlc_status<'a>(
3062                 &self, msg: &msgs::UpdateAddHTLC, shared_secret: [u8; 32], decoded_hop: onion_utils::Hop,
3063                 allow_underpay: bool, next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
3064         ) -> PendingHTLCStatus {
3065                 macro_rules! return_err {
3066                         ($msg: expr, $err_code: expr, $data: expr) => {
3067                                 {
3068                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3069                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3070                                                 channel_id: msg.channel_id,
3071                                                 htlc_id: msg.htlc_id,
3072                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3073                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3074                                         }));
3075                                 }
3076                         }
3077                 }
3078                 match decoded_hop {
3079                         onion_utils::Hop::Receive(next_hop_data) => {
3080                                 // OUR PAYMENT!
3081                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3082                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat)
3083                                 {
3084                                         Ok(info) => {
3085                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3086                                                 // message, however that would leak that we are the recipient of this payment, so
3087                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3088                                                 // delay) once they've send us a commitment_signed!
3089                                                 PendingHTLCStatus::Forward(info)
3090                                         },
3091                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3092                                 }
3093                         },
3094                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3095                                 match self.construct_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3096                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3097                                         Ok(info) => PendingHTLCStatus::Forward(info),
3098                                         Err(InboundOnionErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3099                                 }
3100                         }
3101                 }
3102         }
3103
3104         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3105         /// public, and thus should be called whenever the result is going to be passed out in a
3106         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3107         ///
3108         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3109         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3110         /// storage and the `peer_state` lock has been dropped.
3111         ///
3112         /// [`channel_update`]: msgs::ChannelUpdate
3113         /// [`internal_closing_signed`]: Self::internal_closing_signed
3114         fn get_channel_update_for_broadcast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3115                 if !chan.context.should_announce() {
3116                         return Err(LightningError {
3117                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3118                                 action: msgs::ErrorAction::IgnoreError
3119                         });
3120                 }
3121                 if chan.context.get_short_channel_id().is_none() {
3122                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3123                 }
3124                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", log_bytes!(chan.context.channel_id()));
3125                 self.get_channel_update_for_unicast(chan)
3126         }
3127
3128         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3129         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3130         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3131         /// provided evidence that they know about the existence of the channel.
3132         ///
3133         /// Note that through [`internal_closing_signed`], this function is called without the
3134         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3135         /// removed from the storage and the `peer_state` lock has been dropped.
3136         ///
3137         /// [`channel_update`]: msgs::ChannelUpdate
3138         /// [`internal_closing_signed`]: Self::internal_closing_signed
3139         fn get_channel_update_for_unicast(&self, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3140                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.context.channel_id()));
3141                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3142                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3143                         Some(id) => id,
3144                 };
3145
3146                 self.get_channel_update_for_onion(short_channel_id, chan)
3147         }
3148
3149         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
3150                 log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.context.channel_id()));
3151                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3152
3153                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3154                         ChannelUpdateStatus::Enabled => true,
3155                         ChannelUpdateStatus::DisabledStaged(_) => true,
3156                         ChannelUpdateStatus::Disabled => false,
3157                         ChannelUpdateStatus::EnabledStaged(_) => false,
3158                 };
3159
3160                 let unsigned = msgs::UnsignedChannelUpdate {
3161                         chain_hash: self.genesis_hash,
3162                         short_channel_id,
3163                         timestamp: chan.context.get_update_time_counter(),
3164                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3165                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3166                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3167                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3168                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3169                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3170                         excess_data: Vec::new(),
3171                 };
3172                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3173                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3174                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3175                 // channel.
3176                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3177
3178                 Ok(msgs::ChannelUpdate {
3179                         signature: sig,
3180                         contents: unsigned
3181                 })
3182         }
3183
3184         #[cfg(test)]
3185         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> {
3186                 let _lck = self.total_consistency_lock.read().unwrap();
3187                 self.send_payment_along_path(SendAlongPathArgs {
3188                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3189                         session_priv_bytes
3190                 })
3191         }
3192
3193         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3194                 let SendAlongPathArgs {
3195                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3196                         session_priv_bytes
3197                 } = args;
3198                 // The top-level caller should hold the total_consistency_lock read lock.
3199                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3200
3201                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.hops.first().unwrap().short_channel_id);
3202                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3203                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3204
3205                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
3206                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected".to_owned()})?;
3207                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, recipient_onion, cur_height, keysend_preimage)?;
3208
3209                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash)
3210                         .map_err(|_| APIError::InvalidRoute { err: "Route size too large considering onion data".to_owned()})?;
3211
3212                 let err: Result<(), _> = loop {
3213                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3214                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
3215                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3216                         };
3217
3218                         let per_peer_state = self.per_peer_state.read().unwrap();
3219                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3220                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3221                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3222                         let peer_state = &mut *peer_state_lock;
3223                         if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(id) {
3224                                 if !chan.get().context.is_live() {
3225                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3226                                 }
3227                                 let funding_txo = chan.get().context.get_funding_txo().unwrap();
3228                                 let send_res = chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3229                                         htlc_cltv, HTLCSource::OutboundRoute {
3230                                                 path: path.clone(),
3231                                                 session_priv: session_priv.clone(),
3232                                                 first_hop_htlc_msat: htlc_msat,
3233                                                 payment_id,
3234                                         }, onion_packet, None, &self.fee_estimator, &self.logger);
3235                                 match break_chan_entry!(self, send_res, chan) {
3236                                         Some(monitor_update) => {
3237                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3238                                                         Err(e) => break Err(e),
3239                                                         Ok(false) => {
3240                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3241                                                                 // docs) that we will resend the commitment update once monitor
3242                                                                 // updating completes. Therefore, we must return an error
3243                                                                 // indicating that it is unsafe to retry the payment wholesale,
3244                                                                 // which we do in the send_payment check for
3245                                                                 // MonitorUpdateInProgress, below.
3246                                                                 return Err(APIError::MonitorUpdateInProgress);
3247                                                         },
3248                                                         Ok(true) => {},
3249                                                 }
3250                                         },
3251                                         None => { },
3252                                 }
3253                         } else {
3254                                 // The channel was likely removed after we fetched the id from the
3255                                 // `short_to_chan_info` map, but before we successfully locked the
3256                                 // `channel_by_id` map.
3257                                 // This can occur as no consistency guarantees exists between the two maps.
3258                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3259                         }
3260                         return Ok(());
3261                 };
3262
3263                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3264                         Ok(_) => unreachable!(),
3265                         Err(e) => {
3266                                 Err(APIError::ChannelUnavailable { err: e.err })
3267                         },
3268                 }
3269         }
3270
3271         /// Sends a payment along a given route.
3272         ///
3273         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3274         /// fields for more info.
3275         ///
3276         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3277         /// [`PeerManager::process_events`]).
3278         ///
3279         /// # Avoiding Duplicate Payments
3280         ///
3281         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3282         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3283         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3284         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3285         /// second payment with the same [`PaymentId`].
3286         ///
3287         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3288         /// tracking of payments, including state to indicate once a payment has completed. Because you
3289         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3290         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3291         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3292         ///
3293         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3294         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3295         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3296         /// [`ChannelManager::list_recent_payments`] for more information.
3297         ///
3298         /// # Possible Error States on [`PaymentSendFailure`]
3299         ///
3300         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3301         /// each entry matching the corresponding-index entry in the route paths, see
3302         /// [`PaymentSendFailure`] for more info.
3303         ///
3304         /// In general, a path may raise:
3305         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3306         ///    node public key) is specified.
3307         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available for updates
3308         ///    (including due to previous monitor update failure or new permanent monitor update
3309         ///    failure).
3310         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3311         ///    relevant updates.
3312         ///
3313         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3314         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3315         /// different route unless you intend to pay twice!
3316         ///
3317         /// [`RouteHop`]: crate::routing::router::RouteHop
3318         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3319         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3320         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3321         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3322         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3323         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3324                 let best_block_height = self.best_block.read().unwrap().height();
3325                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3326                 self.pending_outbound_payments
3327                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3328                                 &self.entropy_source, &self.node_signer, best_block_height,
3329                                 |args| self.send_payment_along_path(args))
3330         }
3331
3332         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3333         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3334         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3335                 let best_block_height = self.best_block.read().unwrap().height();
3336                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3337                 self.pending_outbound_payments
3338                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3339                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3340                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3341                                 &self.pending_events, |args| self.send_payment_along_path(args))
3342         }
3343
3344         #[cfg(test)]
3345         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> {
3346                 let best_block_height = self.best_block.read().unwrap().height();
3347                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3348                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3349                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3350                         best_block_height, |args| self.send_payment_along_path(args))
3351         }
3352
3353         #[cfg(test)]
3354         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> {
3355                 let best_block_height = self.best_block.read().unwrap().height();
3356                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3357         }
3358
3359         #[cfg(test)]
3360         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3361                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3362         }
3363
3364
3365         /// Signals that no further retries for the given payment should occur. Useful if you have a
3366         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3367         /// retries are exhausted.
3368         ///
3369         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3370         /// as there are no remaining pending HTLCs for this payment.
3371         ///
3372         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3373         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3374         /// determine the ultimate status of a payment.
3375         ///
3376         /// If an [`Event::PaymentFailed`] event is generated and we restart without this
3377         /// [`ChannelManager`] having been persisted, another [`Event::PaymentFailed`] may be generated.
3378         ///
3379         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3380         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3381         pub fn abandon_payment(&self, payment_id: PaymentId) {
3382                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3383                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3384         }
3385
3386         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3387         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3388         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3389         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3390         /// never reach the recipient.
3391         ///
3392         /// See [`send_payment`] documentation for more details on the return value of this function
3393         /// and idempotency guarantees provided by the [`PaymentId`] key.
3394         ///
3395         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3396         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3397         ///
3398         /// [`send_payment`]: Self::send_payment
3399         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3400                 let best_block_height = self.best_block.read().unwrap().height();
3401                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3402                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3403                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3404                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3405         }
3406
3407         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3408         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3409         ///
3410         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3411         /// payments.
3412         ///
3413         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3414         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> {
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_spontaneous_payment(payment_preimage, recipient_onion,
3418                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3419                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3420                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3421         }
3422
3423         /// Send a payment that is probing the given route for liquidity. We calculate the
3424         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3425         /// us to easily discern them from real payments.
3426         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3427                 let best_block_height = self.best_block.read().unwrap().height();
3428                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3429                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3430                         &self.entropy_source, &self.node_signer, best_block_height,
3431                         |args| self.send_payment_along_path(args))
3432         }
3433
3434         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3435         /// payment probe.
3436         #[cfg(test)]
3437         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3438                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3439         }
3440
3441         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3442         /// which checks the correctness of the funding transaction given the associated channel.
3443         fn funding_transaction_generated_intern<FundingOutput: Fn(&OutboundV1Channel<<SP::Target as SignerProvider>::Signer>, &Transaction) -> Result<OutPoint, APIError>>(
3444                 &self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction, find_funding_output: FundingOutput
3445         ) -> Result<(), APIError> {
3446                 let per_peer_state = self.per_peer_state.read().unwrap();
3447                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3448                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3449
3450                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3451                 let peer_state = &mut *peer_state_lock;
3452                 let (chan, msg) = match peer_state.outbound_v1_channel_by_id.remove(temporary_channel_id) {
3453                         Some(chan) => {
3454                                 let funding_txo = find_funding_output(&chan, &funding_transaction)?;
3455
3456                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, &self.logger)
3457                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3458                                                 let channel_id = chan.context.channel_id();
3459                                                 let user_id = chan.context.get_user_id();
3460                                                 let shutdown_res = chan.context.force_shutdown(false);
3461                                                 let channel_capacity = chan.context.get_value_satoshis();
3462                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, user_id, shutdown_res, None, channel_capacity))
3463                                         } else { unreachable!(); });
3464                                 match funding_res {
3465                                         Ok((chan, funding_msg)) => (chan, funding_msg),
3466                                         Err((chan, err)) => {
3467                                                 mem::drop(peer_state_lock);
3468                                                 mem::drop(per_peer_state);
3469
3470                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3471                                                 return Err(APIError::ChannelUnavailable {
3472                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3473                                                 });
3474                                         },
3475                                 }
3476                         },
3477                         None => {
3478                                 return Err(APIError::ChannelUnavailable {
3479                                         err: format!(
3480                                                 "Channel with id {} not found for the passed counterparty node_id {}",
3481                                                 log_bytes!(*temporary_channel_id), counterparty_node_id),
3482                                 })
3483                         },
3484                 };
3485
3486                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3487                         node_id: chan.context.get_counterparty_node_id(),
3488                         msg,
3489                 });
3490                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3491                         hash_map::Entry::Occupied(_) => {
3492                                 panic!("Generated duplicate funding txid?");
3493                         },
3494                         hash_map::Entry::Vacant(e) => {
3495                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
3496                                 if id_to_peer.insert(chan.context.channel_id(), chan.context.get_counterparty_node_id()).is_some() {
3497                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
3498                                 }
3499                                 e.insert(chan);
3500                         }
3501                 }
3502                 Ok(())
3503         }
3504
3505         #[cfg(test)]
3506         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> {
3507                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |_, tx| {
3508                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3509                 })
3510         }
3511
3512         /// Call this upon creation of a funding transaction for the given channel.
3513         ///
3514         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3515         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3516         ///
3517         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3518         /// across the p2p network.
3519         ///
3520         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3521         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3522         ///
3523         /// May panic if the output found in the funding transaction is duplicative with some other
3524         /// channel (note that this should be trivially prevented by using unique funding transaction
3525         /// keys per-channel).
3526         ///
3527         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3528         /// counterparty's signature the funding transaction will automatically be broadcast via the
3529         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3530         ///
3531         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3532         /// not currently support replacing a funding transaction on an existing channel. Instead,
3533         /// create a new channel with a conflicting funding transaction.
3534         ///
3535         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3536         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3537         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3538         /// for more details.
3539         ///
3540         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3541         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3542         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3543                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3544
3545                 for inp in funding_transaction.input.iter() {
3546                         if inp.witness.is_empty() {
3547                                 return Err(APIError::APIMisuseError {
3548                                         err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3549                                 });
3550                         }
3551                 }
3552                 {
3553                         let height = self.best_block.read().unwrap().height();
3554                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3555                         // lower than the next block height. However, the modules constituting our Lightning
3556                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3557                         // module is ahead of LDK, only allow one more block of headroom.
3558                         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 {
3559                                 return Err(APIError::APIMisuseError {
3560                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3561                                 });
3562                         }
3563                 }
3564                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |chan, tx| {
3565                         if tx.output.len() > u16::max_value() as usize {
3566                                 return Err(APIError::APIMisuseError {
3567                                         err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3568                                 });
3569                         }
3570
3571                         let mut output_index = None;
3572                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3573                         for (idx, outp) in tx.output.iter().enumerate() {
3574                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3575                                         if output_index.is_some() {
3576                                                 return Err(APIError::APIMisuseError {
3577                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3578                                                 });
3579                                         }
3580                                         output_index = Some(idx as u16);
3581                                 }
3582                         }
3583                         if output_index.is_none() {
3584                                 return Err(APIError::APIMisuseError {
3585                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3586                                 });
3587                         }
3588                         Ok(OutPoint { txid: tx.txid(), index: output_index.unwrap() })
3589                 })
3590         }
3591
3592         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
3593         ///
3594         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3595         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3596         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3597         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3598         ///
3599         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3600         /// `counterparty_node_id` is provided.
3601         ///
3602         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3603         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3604         ///
3605         /// If an error is returned, none of the updates should be considered applied.
3606         ///
3607         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3608         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3609         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3610         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3611         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3612         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3613         /// [`APIMisuseError`]: APIError::APIMisuseError
3614         pub fn update_partial_channel_config(
3615                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config_update: &ChannelConfigUpdate,
3616         ) -> Result<(), APIError> {
3617                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
3618                         return Err(APIError::APIMisuseError {
3619                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
3620                         });
3621                 }
3622
3623                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3624                 let per_peer_state = self.per_peer_state.read().unwrap();
3625                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3626                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3627                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3628                 let peer_state = &mut *peer_state_lock;
3629                 for channel_id in channel_ids {
3630                         if !peer_state.has_channel(channel_id) {
3631                                 return Err(APIError::ChannelUnavailable {
3632                                         err: format!("Channel with ID {} was not found for the passed counterparty_node_id {}", log_bytes!(*channel_id), counterparty_node_id),
3633                                 });
3634                         };
3635                 }
3636                 for channel_id in channel_ids {
3637                         if let Some(channel) = peer_state.channel_by_id.get_mut(channel_id) {
3638                                 let mut config = channel.context.config();
3639                                 config.apply(config_update);
3640                                 if !channel.context.update_config(&config) {
3641                                         continue;
3642                                 }
3643                                 if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
3644                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
3645                                 } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
3646                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
3647                                                 node_id: channel.context.get_counterparty_node_id(),
3648                                                 msg,
3649                                         });
3650                                 }
3651                                 continue;
3652                         }
3653
3654                         let context = if let Some(channel) = peer_state.inbound_v1_channel_by_id.get_mut(channel_id) {
3655                                 &mut channel.context
3656                         } else if let Some(channel) = peer_state.outbound_v1_channel_by_id.get_mut(channel_id) {
3657                                 &mut channel.context
3658                         } else {
3659                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
3660                                 debug_assert!(false);
3661                                 return Err(APIError::ChannelUnavailable {
3662                                         err: format!(
3663                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
3664                                                 log_bytes!(*channel_id), counterparty_node_id),
3665                                 });
3666                         };
3667                         let mut config = context.config();
3668                         config.apply(config_update);
3669                         // We update the config, but we MUST NOT broadcast a `channel_update` before `channel_ready`
3670                         // which would be the case for pending inbound/outbound channels.
3671                         context.update_config(&config);
3672                 }
3673                 Ok(())
3674         }
3675
3676         /// Atomically updates the [`ChannelConfig`] for the given channels.
3677         ///
3678         /// Once the updates are applied, each eligible channel (advertised with a known short channel
3679         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
3680         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
3681         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
3682         ///
3683         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
3684         /// `counterparty_node_id` is provided.
3685         ///
3686         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
3687         /// below [`MIN_CLTV_EXPIRY_DELTA`].
3688         ///
3689         /// If an error is returned, none of the updates should be considered applied.
3690         ///
3691         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
3692         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
3693         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
3694         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
3695         /// [`ChannelUpdate`]: msgs::ChannelUpdate
3696         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
3697         /// [`APIMisuseError`]: APIError::APIMisuseError
3698         pub fn update_channel_config(
3699                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
3700         ) -> Result<(), APIError> {
3701                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
3702         }
3703
3704         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
3705         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
3706         ///
3707         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
3708         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
3709         ///
3710         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
3711         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
3712         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
3713         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
3714         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
3715         ///
3716         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
3717         /// you from forwarding more than you received. See
3718         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
3719         /// than expected.
3720         ///
3721         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3722         /// backwards.
3723         ///
3724         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
3725         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3726         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
3727         // TODO: when we move to deciding the best outbound channel at forward time, only take
3728         // `next_node_id` and not `next_hop_channel_id`
3729         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> {
3730                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3731
3732                 let next_hop_scid = {
3733                         let peer_state_lock = self.per_peer_state.read().unwrap();
3734                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
3735                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
3736                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3737                         let peer_state = &mut *peer_state_lock;
3738                         match peer_state.channel_by_id.get(next_hop_channel_id) {
3739                                 Some(chan) => {
3740                                         if !chan.context.is_usable() {
3741                                                 return Err(APIError::ChannelUnavailable {
3742                                                         err: format!("Channel with id {} not fully established", log_bytes!(*next_hop_channel_id))
3743                                                 })
3744                                         }
3745                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
3746                                 },
3747                                 None => return Err(APIError::ChannelUnavailable {
3748                                         err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
3749                                                 log_bytes!(*next_hop_channel_id), next_node_id)
3750                                 })
3751                         }
3752                 };
3753
3754                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3755                         .ok_or_else(|| APIError::APIMisuseError {
3756                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3757                         })?;
3758
3759                 let routing = match payment.forward_info.routing {
3760                         PendingHTLCRouting::Forward { onion_packet, .. } => {
3761                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
3762                         },
3763                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
3764                 };
3765                 let skimmed_fee_msat =
3766                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
3767                 let pending_htlc_info = PendingHTLCInfo {
3768                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
3769                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
3770                 };
3771
3772                 let mut per_source_pending_forward = [(
3773                         payment.prev_short_channel_id,
3774                         payment.prev_funding_outpoint,
3775                         payment.prev_user_channel_id,
3776                         vec![(pending_htlc_info, payment.prev_htlc_id)]
3777                 )];
3778                 self.forward_htlcs(&mut per_source_pending_forward);
3779                 Ok(())
3780         }
3781
3782         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
3783         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
3784         ///
3785         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
3786         /// backwards.
3787         ///
3788         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
3789         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
3790                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3791
3792                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
3793                         .ok_or_else(|| APIError::APIMisuseError {
3794                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
3795                         })?;
3796
3797                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
3798                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3799                                 short_channel_id: payment.prev_short_channel_id,
3800                                 user_channel_id: Some(payment.prev_user_channel_id),
3801                                 outpoint: payment.prev_funding_outpoint,
3802                                 htlc_id: payment.prev_htlc_id,
3803                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
3804                                 phantom_shared_secret: None,
3805                         });
3806
3807                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
3808                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
3809                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
3810                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
3811
3812                 Ok(())
3813         }
3814
3815         /// Processes HTLCs which are pending waiting on random forward delay.
3816         ///
3817         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
3818         /// Will likely generate further events.
3819         pub fn process_pending_htlc_forwards(&self) {
3820                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3821
3822                 let mut new_events = VecDeque::new();
3823                 let mut failed_forwards = Vec::new();
3824                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
3825                 {
3826                         let mut forward_htlcs = HashMap::new();
3827                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
3828
3829                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
3830                                 if short_chan_id != 0 {
3831                                         macro_rules! forwarding_channel_not_found {
3832                                                 () => {
3833                                                         for forward_info in pending_forwards.drain(..) {
3834                                                                 match forward_info {
3835                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3836                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3837                                                                                 forward_info: PendingHTLCInfo {
3838                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
3839                                                                                         outgoing_cltv_value, ..
3840                                                                                 }
3841                                                                         }) => {
3842                                                                                 macro_rules! failure_handler {
3843                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
3844                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3845
3846                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3847                                                                                                         short_channel_id: prev_short_channel_id,
3848                                                                                                         user_channel_id: Some(prev_user_channel_id),
3849                                                                                                         outpoint: prev_funding_outpoint,
3850                                                                                                         htlc_id: prev_htlc_id,
3851                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3852                                                                                                         phantom_shared_secret: $phantom_ss,
3853                                                                                                 });
3854
3855                                                                                                 let reason = if $next_hop_unknown {
3856                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
3857                                                                                                 } else {
3858                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
3859                                                                                                 };
3860
3861                                                                                                 failed_forwards.push((htlc_source, payment_hash,
3862                                                                                                         HTLCFailReason::reason($err_code, $err_data),
3863                                                                                                         reason
3864                                                                                                 ));
3865                                                                                                 continue;
3866                                                                                         }
3867                                                                                 }
3868                                                                                 macro_rules! fail_forward {
3869                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3870                                                                                                 {
3871                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
3872                                                                                                 }
3873                                                                                         }
3874                                                                                 }
3875                                                                                 macro_rules! failed_payment {
3876                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
3877                                                                                                 {
3878                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
3879                                                                                                 }
3880                                                                                         }
3881                                                                                 }
3882                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
3883                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
3884                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.genesis_hash) {
3885                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
3886                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
3887                                                                                                         Ok(res) => res,
3888                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
3889                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
3890                                                                                                                 // In this scenario, the phantom would have sent us an
3891                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
3892                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
3893                                                                                                                 // of the onion.
3894                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
3895                                                                                                         },
3896                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
3897                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
3898                                                                                                         },
3899                                                                                                 };
3900                                                                                                 match next_hop {
3901                                                                                                         onion_utils::Hop::Receive(hop_data) => {
3902                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data,
3903                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
3904                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None)
3905                                                                                                                 {
3906                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
3907                                                                                                                         Err(InboundOnionErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
3908                                                                                                                 }
3909                                                                                                         },
3910                                                                                                         _ => panic!(),
3911                                                                                                 }
3912                                                                                         } else {
3913                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3914                                                                                         }
3915                                                                                 } else {
3916                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
3917                                                                                 }
3918                                                                         },
3919                                                                         HTLCForwardInfo::FailHTLC { .. } => {
3920                                                                                 // Channel went away before we could fail it. This implies
3921                                                                                 // the channel is now on chain and our counterparty is
3922                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
3923                                                                                 // problem, not ours.
3924                                                                         }
3925                                                                 }
3926                                                         }
3927                                                 }
3928                                         }
3929                                         let (counterparty_node_id, forward_chan_id) = match self.short_to_chan_info.read().unwrap().get(&short_chan_id) {
3930                                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3931                                                 None => {
3932                                                         forwarding_channel_not_found!();
3933                                                         continue;
3934                                                 }
3935                                         };
3936                                         let per_peer_state = self.per_peer_state.read().unwrap();
3937                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3938                                         if peer_state_mutex_opt.is_none() {
3939                                                 forwarding_channel_not_found!();
3940                                                 continue;
3941                                         }
3942                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3943                                         let peer_state = &mut *peer_state_lock;
3944                                         match peer_state.channel_by_id.entry(forward_chan_id) {
3945                                                 hash_map::Entry::Vacant(_) => {
3946                                                         forwarding_channel_not_found!();
3947                                                         continue;
3948                                                 },
3949                                                 hash_map::Entry::Occupied(mut chan) => {
3950                                                         for forward_info in pending_forwards.drain(..) {
3951                                                                 match forward_info {
3952                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
3953                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
3954                                                                                 forward_info: PendingHTLCInfo {
3955                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
3956                                                                                         routing: PendingHTLCRouting::Forward { onion_packet, .. }, skimmed_fee_msat, ..
3957                                                                                 },
3958                                                                         }) => {
3959                                                                                 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);
3960                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
3961                                                                                         short_channel_id: prev_short_channel_id,
3962                                                                                         user_channel_id: Some(prev_user_channel_id),
3963                                                                                         outpoint: prev_funding_outpoint,
3964                                                                                         htlc_id: prev_htlc_id,
3965                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
3966                                                                                         // Phantom payments are only PendingHTLCRouting::Receive.
3967                                                                                         phantom_shared_secret: None,
3968                                                                                 });
3969                                                                                 if let Err(e) = chan.get_mut().queue_add_htlc(outgoing_amt_msat,
3970                                                                                         payment_hash, outgoing_cltv_value, htlc_source.clone(),
3971                                                                                         onion_packet, skimmed_fee_msat, &self.fee_estimator,
3972                                                                                         &self.logger)
3973                                                                                 {
3974                                                                                         if let ChannelError::Ignore(msg) = e {
3975                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
3976                                                                                         } else {
3977                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
3978                                                                                         }
3979                                                                                         let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
3980                                                                                         failed_forwards.push((htlc_source, payment_hash,
3981                                                                                                 HTLCFailReason::reason(failure_code, data),
3982                                                                                                 HTLCDestination::NextHopChannel { node_id: Some(chan.get().context.get_counterparty_node_id()), channel_id: forward_chan_id }
3983                                                                                         ));
3984                                                                                         continue;
3985                                                                                 }
3986                                                                         },
3987                                                                         HTLCForwardInfo::AddHTLC { .. } => {
3988                                                                                 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
3989                                                                         },
3990                                                                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
3991                                                                                 log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
3992                                                                                 if let Err(e) = chan.get_mut().queue_fail_htlc(
3993                                                                                         htlc_id, err_packet, &self.logger
3994                                                                                 ) {
3995                                                                                         if let ChannelError::Ignore(msg) = e {
3996                                                                                                 log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
3997                                                                                         } else {
3998                                                                                                 panic!("Stated return value requirements in queue_fail_htlc() were not met");
3999                                                                                         }
4000                                                                                         // fail-backs are best-effort, we probably already have one
4001                                                                                         // pending, and if not that's OK, if not, the channel is on
4002                                                                                         // the chain and sending the HTLC-Timeout is their problem.
4003                                                                                         continue;
4004                                                                                 }
4005                                                                         },
4006                                                                 }
4007                                                         }
4008                                                 }
4009                                         }
4010                                 } else {
4011                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4012                                                 match forward_info {
4013                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4014                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
4015                                                                 forward_info: PendingHTLCInfo {
4016                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4017                                                                         skimmed_fee_msat, ..
4018                                                                 }
4019                                                         }) => {
4020                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4021                                                                         PendingHTLCRouting::Receive { payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret, custom_tlvs } => {
4022                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4023                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4024                                                                                                 payment_metadata, custom_tlvs };
4025                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4026                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4027                                                                         },
4028                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4029                                                                                 let onion_fields = RecipientOnionFields {
4030                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4031                                                                                         payment_metadata,
4032                                                                                         custom_tlvs,
4033                                                                                 };
4034                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4035                                                                                         payment_data, None, onion_fields)
4036                                                                         },
4037                                                                         _ => {
4038                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4039                                                                         }
4040                                                                 };
4041                                                                 let claimable_htlc = ClaimableHTLC {
4042                                                                         prev_hop: HTLCPreviousHopData {
4043                                                                                 short_channel_id: prev_short_channel_id,
4044                                                                                 user_channel_id: Some(prev_user_channel_id),
4045                                                                                 outpoint: prev_funding_outpoint,
4046                                                                                 htlc_id: prev_htlc_id,
4047                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4048                                                                                 phantom_shared_secret,
4049                                                                         },
4050                                                                         // We differentiate the received value from the sender intended value
4051                                                                         // if possible so that we don't prematurely mark MPP payments complete
4052                                                                         // if routing nodes overpay
4053                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4054                                                                         sender_intended_value: outgoing_amt_msat,
4055                                                                         timer_ticks: 0,
4056                                                                         total_value_received: None,
4057                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4058                                                                         cltv_expiry,
4059                                                                         onion_payload,
4060                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4061                                                                 };
4062
4063                                                                 let mut committed_to_claimable = false;
4064
4065                                                                 macro_rules! fail_htlc {
4066                                                                         ($htlc: expr, $payment_hash: expr) => {
4067                                                                                 debug_assert!(!committed_to_claimable);
4068                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4069                                                                                 htlc_msat_height_data.extend_from_slice(
4070                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4071                                                                                 );
4072                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4073                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4074                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4075                                                                                                 outpoint: prev_funding_outpoint,
4076                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4077                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4078                                                                                                 phantom_shared_secret,
4079                                                                                         }), payment_hash,
4080                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4081                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4082                                                                                 ));
4083                                                                                 continue 'next_forwardable_htlc;
4084                                                                         }
4085                                                                 }
4086                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4087                                                                 let mut receiver_node_id = self.our_network_pubkey;
4088                                                                 if phantom_shared_secret.is_some() {
4089                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4090                                                                                 .expect("Failed to get node_id for phantom node recipient");
4091                                                                 }
4092
4093                                                                 macro_rules! check_total_value {
4094                                                                         ($purpose: expr) => {{
4095                                                                                 let mut payment_claimable_generated = false;
4096                                                                                 let is_keysend = match $purpose {
4097                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4098                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4099                                                                                 };
4100                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4101                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4102                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4103                                                                                 }
4104                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4105                                                                                         .entry(payment_hash)
4106                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4107                                                                                         .or_insert_with(|| {
4108                                                                                                 committed_to_claimable = true;
4109                                                                                                 ClaimablePayment {
4110                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4111                                                                                                 }
4112                                                                                         });
4113                                                                                 if $purpose != claimable_payment.purpose {
4114                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4115                                                                                         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));
4116                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4117                                                                                 }
4118                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4119                                                                                         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));
4120                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4121                                                                                 }
4122                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4123                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4124                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4125                                                                                         }
4126                                                                                 } else {
4127                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4128                                                                                 }
4129                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4130                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4131                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4132                                                                                 for htlc in htlcs.iter() {
4133                                                                                         total_value += htlc.sender_intended_value;
4134                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4135                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4136                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4137                                                                                                         log_bytes!(payment_hash.0), claimable_htlc.total_msat, htlc.total_msat);
4138                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4139                                                                                         }
4140                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4141                                                                                 }
4142                                                                                 // The condition determining whether an MPP is complete must
4143                                                                                 // match exactly the condition used in `timer_tick_occurred`
4144                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4145                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4146                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4147                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4148                                                                                                 log_bytes!(payment_hash.0));
4149                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4150                                                                                 } else if total_value >= claimable_htlc.total_msat {
4151                                                                                         #[allow(unused_assignments)] {
4152                                                                                                 committed_to_claimable = true;
4153                                                                                         }
4154                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
4155                                                                                         htlcs.push(claimable_htlc);
4156                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4157                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4158                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4159                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4160                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4161                                                                                                 counterparty_skimmed_fee_msat);
4162                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4163                                                                                                 receiver_node_id: Some(receiver_node_id),
4164                                                                                                 payment_hash,
4165                                                                                                 purpose: $purpose,
4166                                                                                                 amount_msat,
4167                                                                                                 counterparty_skimmed_fee_msat,
4168                                                                                                 via_channel_id: Some(prev_channel_id),
4169                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4170                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4171                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4172                                                                                         }, None));
4173                                                                                         payment_claimable_generated = true;
4174                                                                                 } else {
4175                                                                                         // Nothing to do - we haven't reached the total
4176                                                                                         // payment value yet, wait until we receive more
4177                                                                                         // MPP parts.
4178                                                                                         htlcs.push(claimable_htlc);
4179                                                                                         #[allow(unused_assignments)] {
4180                                                                                                 committed_to_claimable = true;
4181                                                                                         }
4182                                                                                 }
4183                                                                                 payment_claimable_generated
4184                                                                         }}
4185                                                                 }
4186
4187                                                                 // Check that the payment hash and secret are known. Note that we
4188                                                                 // MUST take care to handle the "unknown payment hash" and
4189                                                                 // "incorrect payment secret" cases here identically or we'd expose
4190                                                                 // that we are the ultimate recipient of the given payment hash.
4191                                                                 // Further, we must not expose whether we have any other HTLCs
4192                                                                 // associated with the same payment_hash pending or not.
4193                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4194                                                                 match payment_secrets.entry(payment_hash) {
4195                                                                         hash_map::Entry::Vacant(_) => {
4196                                                                                 match claimable_htlc.onion_payload {
4197                                                                                         OnionPayload::Invoice { .. } => {
4198                                                                                                 let payment_data = payment_data.unwrap();
4199                                                                                                 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) {
4200                                                                                                         Ok(result) => result,
4201                                                                                                         Err(()) => {
4202                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", log_bytes!(payment_hash.0));
4203                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4204                                                                                                         }
4205                                                                                                 };
4206                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4207                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4208                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4209                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4210                                                                                                                         log_bytes!(payment_hash.0), cltv_expiry, expected_min_expiry_height);
4211                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4212                                                                                                         }
4213                                                                                                 }
4214                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4215                                                                                                         payment_preimage: payment_preimage.clone(),
4216                                                                                                         payment_secret: payment_data.payment_secret,
4217                                                                                                 };
4218                                                                                                 check_total_value!(purpose);
4219                                                                                         },
4220                                                                                         OnionPayload::Spontaneous(preimage) => {
4221                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4222                                                                                                 check_total_value!(purpose);
4223                                                                                         }
4224                                                                                 }
4225                                                                         },
4226                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4227                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4228                                                                                         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));
4229                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4230                                                                                 }
4231                                                                                 let payment_data = payment_data.unwrap();
4232                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4233                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", log_bytes!(payment_hash.0));
4234                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4235                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4236                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4237                                                                                                 log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4238                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4239                                                                                 } else {
4240                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4241                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4242                                                                                                 payment_secret: payment_data.payment_secret,
4243                                                                                         };
4244                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4245                                                                                         if payment_claimable_generated {
4246                                                                                                 inbound_payment.remove_entry();
4247                                                                                         }
4248                                                                                 }
4249                                                                         },
4250                                                                 };
4251                                                         },
4252                                                         HTLCForwardInfo::FailHTLC { .. } => {
4253                                                                 panic!("Got pending fail of our own HTLC");
4254                                                         }
4255                                                 }
4256                                         }
4257                                 }
4258                         }
4259                 }
4260
4261                 let best_block_height = self.best_block.read().unwrap().height();
4262                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4263                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4264                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4265
4266                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4267                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4268                 }
4269                 self.forward_htlcs(&mut phantom_receives);
4270
4271                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4272                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4273                 // nice to do the work now if we can rather than while we're trying to get messages in the
4274                 // network stack.
4275                 self.check_free_holding_cells();
4276
4277                 if new_events.is_empty() { return }
4278                 let mut events = self.pending_events.lock().unwrap();
4279                 events.append(&mut new_events);
4280         }
4281
4282         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4283         ///
4284         /// Expects the caller to have a total_consistency_lock read lock.
4285         fn process_background_events(&self) -> NotifyOption {
4286                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4287
4288                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4289
4290                 let mut background_events = Vec::new();
4291                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4292                 if background_events.is_empty() {
4293                         return NotifyOption::SkipPersist;
4294                 }
4295
4296                 for event in background_events.drain(..) {
4297                         match event {
4298                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, update)) => {
4299                                         // The channel has already been closed, so no use bothering to care about the
4300                                         // monitor updating completing.
4301                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4302                                 },
4303                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, update } => {
4304                                         let mut updated_chan = false;
4305                                         let res = {
4306                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4307                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4308                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4309                                                         let peer_state = &mut *peer_state_lock;
4310                                                         match peer_state.channel_by_id.entry(funding_txo.to_channel_id()) {
4311                                                                 hash_map::Entry::Occupied(mut chan) => {
4312                                                                         updated_chan = true;
4313                                                                         handle_new_monitor_update!(self, funding_txo, update.clone(),
4314                                                                                 peer_state_lock, peer_state, per_peer_state, chan).map(|_| ())
4315                                                                 },
4316                                                                 hash_map::Entry::Vacant(_) => Ok(()),
4317                                                         }
4318                                                 } else { Ok(()) }
4319                                         };
4320                                         if !updated_chan {
4321                                                 // TODO: Track this as in-flight even though the channel is closed.
4322                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4323                                         }
4324                                         // TODO: If this channel has since closed, we're likely providing a payment
4325                                         // preimage update, which we must ensure is durable! We currently don't,
4326                                         // however, ensure that.
4327                                         if res.is_err() {
4328                                                 log_error!(self.logger,
4329                                                         "Failed to provide ChannelMonitorUpdate to closed channel! This likely lost us a payment preimage!");
4330                                         }
4331                                         let _ = handle_error!(self, res, counterparty_node_id);
4332                                 },
4333                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4334                                         let per_peer_state = self.per_peer_state.read().unwrap();
4335                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4336                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4337                                                 let peer_state = &mut *peer_state_lock;
4338                                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&channel_id) {
4339                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4340                                                 } else {
4341                                                         let update_actions = peer_state.monitor_update_blocked_actions
4342                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4343                                                         mem::drop(peer_state_lock);
4344                                                         mem::drop(per_peer_state);
4345                                                         self.handle_monitor_update_completion_actions(update_actions);
4346                                                 }
4347                                         }
4348                                 },
4349                         }
4350                 }
4351                 NotifyOption::DoPersist
4352         }
4353
4354         #[cfg(any(test, feature = "_test_utils"))]
4355         /// Process background events, for functional testing
4356         pub fn test_process_background_events(&self) {
4357                 let _lck = self.total_consistency_lock.read().unwrap();
4358                 let _ = self.process_background_events();
4359         }
4360
4361         fn update_channel_fee(&self, chan_id: &[u8; 32], chan: &mut Channel<<SP::Target as SignerProvider>::Signer>, new_feerate: u32) -> NotifyOption {
4362                 if !chan.context.is_outbound() { return NotifyOption::SkipPersist; }
4363                 // If the feerate has decreased by less than half, don't bother
4364                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4365                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4366                                 log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4367                         return NotifyOption::SkipPersist;
4368                 }
4369                 if !chan.context.is_live() {
4370                         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).",
4371                                 log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4372                         return NotifyOption::SkipPersist;
4373                 }
4374                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
4375                         log_bytes!(chan_id[..]), chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4376
4377                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &self.logger);
4378                 NotifyOption::DoPersist
4379         }
4380
4381         #[cfg(fuzzing)]
4382         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4383         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4384         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4385         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4386         pub fn maybe_update_chan_fees(&self) {
4387                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
4388                         let mut should_persist = self.process_background_events();
4389
4390                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4391                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4392
4393                         let per_peer_state = self.per_peer_state.read().unwrap();
4394                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4395                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4396                                 let peer_state = &mut *peer_state_lock;
4397                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
4398                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4399                                                 min_mempool_feerate
4400                                         } else {
4401                                                 normal_feerate
4402                                         };
4403                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4404                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4405                                 }
4406                         }
4407
4408                         should_persist
4409                 });
4410         }
4411
4412         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4413         ///
4414         /// This currently includes:
4415         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4416         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4417         ///    than a minute, informing the network that they should no longer attempt to route over
4418         ///    the channel.
4419         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4420         ///    with the current [`ChannelConfig`].
4421         ///  * Removing peers which have disconnected but and no longer have any channels.
4422         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4423         ///
4424         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4425         /// estimate fetches.
4426         ///
4427         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4428         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4429         pub fn timer_tick_occurred(&self) {
4430                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
4431                         let mut should_persist = self.process_background_events();
4432
4433                         let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4434                         let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4435
4436                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4437                         let mut timed_out_mpp_htlcs = Vec::new();
4438                         let mut pending_peers_awaiting_removal = Vec::new();
4439                         {
4440                                 let per_peer_state = self.per_peer_state.read().unwrap();
4441                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4442                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4443                                         let peer_state = &mut *peer_state_lock;
4444                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4445                                         let counterparty_node_id = *counterparty_node_id;
4446                                         peer_state.channel_by_id.retain(|chan_id, chan| {
4447                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4448                                                         min_mempool_feerate
4449                                                 } else {
4450                                                         normal_feerate
4451                                                 };
4452                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4453                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4454
4455                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4456                                                         let (needs_close, err) = convert_chan_err!(self, e, chan, chan_id);
4457                                                         handle_errors.push((Err(err), counterparty_node_id));
4458                                                         if needs_close { return false; }
4459                                                 }
4460
4461                                                 match chan.channel_update_status() {
4462                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4463                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4464                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4465                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4466                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4467                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4468                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4469                                                                 n += 1;
4470                                                                 if n >= DISABLE_GOSSIP_TICKS {
4471                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4472                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4473                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4474                                                                                         msg: update
4475                                                                                 });
4476                                                                         }
4477                                                                         should_persist = NotifyOption::DoPersist;
4478                                                                 } else {
4479                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4480                                                                 }
4481                                                         },
4482                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4483                                                                 n += 1;
4484                                                                 if n >= ENABLE_GOSSIP_TICKS {
4485                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4486                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4487                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4488                                                                                         msg: update
4489                                                                                 });
4490                                                                         }
4491                                                                         should_persist = NotifyOption::DoPersist;
4492                                                                 } else {
4493                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4494                                                                 }
4495                                                         },
4496                                                         _ => {},
4497                                                 }
4498
4499                                                 chan.context.maybe_expire_prev_config();
4500
4501                                                 if chan.should_disconnect_peer_awaiting_response() {
4502                                                         log_debug!(self.logger, "Disconnecting peer {} due to not making any progress on channel {}",
4503                                                                         counterparty_node_id, log_bytes!(*chan_id));
4504                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4505                                                                 node_id: counterparty_node_id,
4506                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
4507                                                                         msg: msgs::WarningMessage {
4508                                                                                 channel_id: *chan_id,
4509                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
4510                                                                         },
4511                                                                 },
4512                                                         });
4513                                                 }
4514
4515                                                 true
4516                                         });
4517
4518                                         let process_unfunded_channel_tick = |
4519                                                 chan_id: &[u8; 32],
4520                                                 chan_context: &mut ChannelContext<<SP::Target as SignerProvider>::Signer>,
4521                                                 unfunded_chan_context: &mut UnfundedChannelContext,
4522                                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4523                                         | {
4524                                                 chan_context.maybe_expire_prev_config();
4525                                                 if unfunded_chan_context.should_expire_unfunded_channel() {
4526                                                         log_error!(self.logger,
4527                                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner",
4528                                                                 log_bytes!(&chan_id[..]));
4529                                                         update_maps_on_chan_removal!(self, &chan_context);
4530                                                         self.issue_channel_close_events(&chan_context, ClosureReason::HolderForceClosed);
4531                                                         self.finish_force_close_channel(chan_context.force_shutdown(false));
4532                                                         pending_msg_events.push(MessageSendEvent::HandleError {
4533                                                                 node_id: counterparty_node_id,
4534                                                                 action: msgs::ErrorAction::SendErrorMessage {
4535                                                                         msg: msgs::ErrorMessage {
4536                                                                                 channel_id: *chan_id,
4537                                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4538                                                                         },
4539                                                                 },
4540                                                         });
4541                                                         false
4542                                                 } else {
4543                                                         true
4544                                                 }
4545                                         };
4546                                         peer_state.outbound_v1_channel_by_id.retain(|chan_id, chan| process_unfunded_channel_tick(
4547                                                 chan_id, &mut chan.context, &mut chan.unfunded_context, pending_msg_events));
4548                                         peer_state.inbound_v1_channel_by_id.retain(|chan_id, chan| process_unfunded_channel_tick(
4549                                                 chan_id, &mut chan.context, &mut chan.unfunded_context, pending_msg_events));
4550
4551                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
4552                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
4553                                                         log_error!(self.logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", log_bytes!(&chan_id[..]));
4554                                                         peer_state.pending_msg_events.push(
4555                                                                 events::MessageSendEvent::HandleError {
4556                                                                         node_id: counterparty_node_id,
4557                                                                         action: msgs::ErrorAction::SendErrorMessage {
4558                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
4559                                                                         },
4560                                                                 }
4561                                                         );
4562                                                 }
4563                                         }
4564                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
4565
4566                                         if peer_state.ok_to_remove(true) {
4567                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
4568                                         }
4569                                 }
4570                         }
4571
4572                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
4573                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
4574                         // of to that peer is later closed while still being disconnected (i.e. force closed),
4575                         // we therefore need to remove the peer from `peer_state` separately.
4576                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
4577                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
4578                         // negative effects on parallelism as much as possible.
4579                         if pending_peers_awaiting_removal.len() > 0 {
4580                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
4581                                 for counterparty_node_id in pending_peers_awaiting_removal {
4582                                         match per_peer_state.entry(counterparty_node_id) {
4583                                                 hash_map::Entry::Occupied(entry) => {
4584                                                         // Remove the entry if the peer is still disconnected and we still
4585                                                         // have no channels to the peer.
4586                                                         let remove_entry = {
4587                                                                 let peer_state = entry.get().lock().unwrap();
4588                                                                 peer_state.ok_to_remove(true)
4589                                                         };
4590                                                         if remove_entry {
4591                                                                 entry.remove_entry();
4592                                                         }
4593                                                 },
4594                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
4595                                         }
4596                                 }
4597                         }
4598
4599                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
4600                                 if payment.htlcs.is_empty() {
4601                                         // This should be unreachable
4602                                         debug_assert!(false);
4603                                         return false;
4604                                 }
4605                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
4606                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
4607                                         // In this case we're not going to handle any timeouts of the parts here.
4608                                         // This condition determining whether the MPP is complete here must match
4609                                         // exactly the condition used in `process_pending_htlc_forwards`.
4610                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
4611                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
4612                                         {
4613                                                 return true;
4614                                         } else if payment.htlcs.iter_mut().any(|htlc| {
4615                                                 htlc.timer_ticks += 1;
4616                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
4617                                         }) {
4618                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
4619                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
4620                                                 return false;
4621                                         }
4622                                 }
4623                                 true
4624                         });
4625
4626                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
4627                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
4628                                 let reason = HTLCFailReason::from_failure_code(23);
4629                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
4630                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
4631                         }
4632
4633                         for (err, counterparty_node_id) in handle_errors.drain(..) {
4634                                 let _ = handle_error!(self, err, counterparty_node_id);
4635                         }
4636
4637                         self.pending_outbound_payments.remove_stale_resolved_payments(&self.pending_events);
4638
4639                         // Technically we don't need to do this here, but if we have holding cell entries in a
4640                         // channel that need freeing, it's better to do that here and block a background task
4641                         // than block the message queueing pipeline.
4642                         if self.check_free_holding_cells() {
4643                                 should_persist = NotifyOption::DoPersist;
4644                         }
4645
4646                         should_persist
4647                 });
4648         }
4649
4650         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
4651         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
4652         /// along the path (including in our own channel on which we received it).
4653         ///
4654         /// Note that in some cases around unclean shutdown, it is possible the payment may have
4655         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
4656         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
4657         /// may have already been failed automatically by LDK if it was nearing its expiration time.
4658         ///
4659         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
4660         /// [`ChannelManager::claim_funds`]), you should still monitor for
4661         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
4662         /// startup during which time claims that were in-progress at shutdown may be replayed.
4663         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
4664                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
4665         }
4666
4667         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
4668         /// reason for the failure.
4669         ///
4670         /// See [`FailureCode`] for valid failure codes.
4671         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
4672                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4673
4674                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
4675                 if let Some(payment) = removed_source {
4676                         for htlc in payment.htlcs {
4677                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
4678                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4679                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
4680                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4681                         }
4682                 }
4683         }
4684
4685         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
4686         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
4687                 match failure_code {
4688                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
4689                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
4690                         FailureCode::IncorrectOrUnknownPaymentDetails => {
4691                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4692                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4693                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
4694                         },
4695                         FailureCode::InvalidOnionPayload(data) => {
4696                                 let fail_data = match data {
4697                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
4698                                         None => Vec::new(),
4699                                 };
4700                                 HTLCFailReason::reason(failure_code.into(), fail_data)
4701                         }
4702                 }
4703         }
4704
4705         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4706         /// that we want to return and a channel.
4707         ///
4708         /// This is for failures on the channel on which the HTLC was *received*, not failures
4709         /// forwarding
4710         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<<SP::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
4711                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
4712                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
4713                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
4714                 // an inbound SCID alias before the real SCID.
4715                 let scid_pref = if chan.context.should_announce() {
4716                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
4717                 } else {
4718                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
4719                 };
4720                 if let Some(scid) = scid_pref {
4721                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
4722                 } else {
4723                         (0x4000|10, Vec::new())
4724                 }
4725         }
4726
4727
4728         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
4729         /// that we want to return and a channel.
4730         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>) {
4731                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
4732                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
4733                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
4734                         if desired_err_code == 0x1000 | 20 {
4735                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
4736                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
4737                                 0u16.write(&mut enc).expect("Writes cannot fail");
4738                         }
4739                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
4740                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
4741                         upd.write(&mut enc).expect("Writes cannot fail");
4742                         (desired_err_code, enc.0)
4743                 } else {
4744                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
4745                         // which means we really shouldn't have gotten a payment to be forwarded over this
4746                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
4747                         // PERM|no_such_channel should be fine.
4748                         (0x4000|10, Vec::new())
4749                 }
4750         }
4751
4752         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
4753         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
4754         // be surfaced to the user.
4755         fn fail_holding_cell_htlcs(
4756                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32],
4757                 counterparty_node_id: &PublicKey
4758         ) {
4759                 let (failure_code, onion_failure_data) = {
4760                         let per_peer_state = self.per_peer_state.read().unwrap();
4761                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
4762                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4763                                 let peer_state = &mut *peer_state_lock;
4764                                 match peer_state.channel_by_id.entry(channel_id) {
4765                                         hash_map::Entry::Occupied(chan_entry) => {
4766                                                 self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
4767                                         },
4768                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
4769                                 }
4770                         } else { (0x4000|10, Vec::new()) }
4771                 };
4772
4773                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
4774                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
4775                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
4776                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
4777                 }
4778         }
4779
4780         /// Fails an HTLC backwards to the sender of it to us.
4781         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
4782         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
4783                 // Ensure that no peer state channel storage lock is held when calling this function.
4784                 // This ensures that future code doesn't introduce a lock-order requirement for
4785                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
4786                 // this function with any `per_peer_state` peer lock acquired would.
4787                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
4788                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
4789                 }
4790
4791                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
4792                 //identify whether we sent it or not based on the (I presume) very different runtime
4793                 //between the branches here. We should make this async and move it into the forward HTLCs
4794                 //timer handling.
4795
4796                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
4797                 // from block_connected which may run during initialization prior to the chain_monitor
4798                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
4799                 match source {
4800                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
4801                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
4802                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
4803                                         &self.pending_events, &self.logger)
4804                                 { self.push_pending_forwards_ev(); }
4805                         },
4806                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint, .. }) => {
4807                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", log_bytes!(payment_hash.0), onion_error);
4808                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
4809
4810                                 let mut push_forward_ev = false;
4811                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
4812                                 if forward_htlcs.is_empty() {
4813                                         push_forward_ev = true;
4814                                 }
4815                                 match forward_htlcs.entry(*short_channel_id) {
4816                                         hash_map::Entry::Occupied(mut entry) => {
4817                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
4818                                         },
4819                                         hash_map::Entry::Vacant(entry) => {
4820                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
4821                                         }
4822                                 }
4823                                 mem::drop(forward_htlcs);
4824                                 if push_forward_ev { self.push_pending_forwards_ev(); }
4825                                 let mut pending_events = self.pending_events.lock().unwrap();
4826                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
4827                                         prev_channel_id: outpoint.to_channel_id(),
4828                                         failed_next_destination: destination,
4829                                 }, None));
4830                         },
4831                 }
4832         }
4833
4834         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
4835         /// [`MessageSendEvent`]s needed to claim the payment.
4836         ///
4837         /// This method is guaranteed to ensure the payment has been claimed but only if the current
4838         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
4839         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
4840         /// successful. It will generally be available in the next [`process_pending_events`] call.
4841         ///
4842         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
4843         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
4844         /// event matches your expectation. If you fail to do so and call this method, you may provide
4845         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
4846         ///
4847         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
4848         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
4849         /// [`claim_funds_with_known_custom_tlvs`].
4850         ///
4851         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
4852         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
4853         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
4854         /// [`process_pending_events`]: EventsProvider::process_pending_events
4855         /// [`create_inbound_payment`]: Self::create_inbound_payment
4856         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
4857         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
4858         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
4859                 self.claim_payment_internal(payment_preimage, false);
4860         }
4861
4862         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
4863         /// even type numbers.
4864         ///
4865         /// # Note
4866         ///
4867         /// You MUST check you've understood all even TLVs before using this to
4868         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
4869         ///
4870         /// [`claim_funds`]: Self::claim_funds
4871         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
4872                 self.claim_payment_internal(payment_preimage, true);
4873         }
4874
4875         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
4876                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
4877
4878                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4879
4880                 let mut sources = {
4881                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
4882                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
4883                                 let mut receiver_node_id = self.our_network_pubkey;
4884                                 for htlc in payment.htlcs.iter() {
4885                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
4886                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
4887                                                         .expect("Failed to get node_id for phantom node recipient");
4888                                                 receiver_node_id = phantom_pubkey;
4889                                                 break;
4890                                         }
4891                                 }
4892
4893                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
4894                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
4895                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
4896                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
4897                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
4898                                 });
4899                                 if dup_purpose.is_some() {
4900                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
4901                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
4902                                                 log_bytes!(payment_hash.0));
4903                                 }
4904
4905                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
4906                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
4907                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
4908                                                         log_bytes!(payment_hash.0), log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
4909                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
4910                                                 mem::drop(claimable_payments);
4911                                                 for htlc in payment.htlcs {
4912                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
4913                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4914                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
4915                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4916                                                 }
4917                                                 return;
4918                                         }
4919                                 }
4920
4921                                 payment.htlcs
4922                         } else { return; }
4923                 };
4924                 debug_assert!(!sources.is_empty());
4925
4926                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
4927                 // and when we got here we need to check that the amount we're about to claim matches the
4928                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
4929                 // the MPP parts all have the same `total_msat`.
4930                 let mut claimable_amt_msat = 0;
4931                 let mut prev_total_msat = None;
4932                 let mut expected_amt_msat = None;
4933                 let mut valid_mpp = true;
4934                 let mut errs = Vec::new();
4935                 let per_peer_state = self.per_peer_state.read().unwrap();
4936                 for htlc in sources.iter() {
4937                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
4938                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
4939                                 debug_assert!(false);
4940                                 valid_mpp = false;
4941                                 break;
4942                         }
4943                         prev_total_msat = Some(htlc.total_msat);
4944
4945                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
4946                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
4947                                 debug_assert!(false);
4948                                 valid_mpp = false;
4949                                 break;
4950                         }
4951                         expected_amt_msat = htlc.total_value_received;
4952                         claimable_amt_msat += htlc.value;
4953                 }
4954                 mem::drop(per_peer_state);
4955                 if sources.is_empty() || expected_amt_msat.is_none() {
4956                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4957                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
4958                         return;
4959                 }
4960                 if claimable_amt_msat != expected_amt_msat.unwrap() {
4961                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4962                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
4963                                 expected_amt_msat.unwrap(), claimable_amt_msat);
4964                         return;
4965                 }
4966                 if valid_mpp {
4967                         for htlc in sources.drain(..) {
4968                                 if let Err((pk, err)) = self.claim_funds_from_hop(
4969                                         htlc.prev_hop, payment_preimage,
4970                                         |_| Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash }))
4971                                 {
4972                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
4973                                                 // We got a temporary failure updating monitor, but will claim the
4974                                                 // HTLC when the monitor updating is restored (or on chain).
4975                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
4976                                         } else { errs.push((pk, err)); }
4977                                 }
4978                         }
4979                 }
4980                 if !valid_mpp {
4981                         for htlc in sources.drain(..) {
4982                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
4983                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
4984                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
4985                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
4986                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
4987                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
4988                         }
4989                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
4990                 }
4991
4992                 // Now we can handle any errors which were generated.
4993                 for (counterparty_node_id, err) in errs.drain(..) {
4994                         let res: Result<(), _> = Err(err);
4995                         let _ = handle_error!(self, res, counterparty_node_id);
4996                 }
4997         }
4998
4999         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>) -> Option<MonitorUpdateCompletionAction>>(&self,
5000                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5001         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5002                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5003
5004                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5005                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5006                 // `BackgroundEvent`s.
5007                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5008
5009                 {
5010                         let per_peer_state = self.per_peer_state.read().unwrap();
5011                         let chan_id = prev_hop.outpoint.to_channel_id();
5012                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5013                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5014                                 None => None
5015                         };
5016
5017                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5018                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5019                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5020                         ).unwrap_or(None);
5021
5022                         if peer_state_opt.is_some() {
5023                                 let mut peer_state_lock = peer_state_opt.unwrap();
5024                                 let peer_state = &mut *peer_state_lock;
5025                                 if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(chan_id) {
5026                                         let counterparty_node_id = chan.get().context.get_counterparty_node_id();
5027                                         let fulfill_res = chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger);
5028
5029                                         if let UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } = fulfill_res {
5030                                                 if let Some(action) = completion_action(Some(htlc_value_msat)) {
5031                                                         log_trace!(self.logger, "Tracking monitor update completion action for channel {}: {:?}",
5032                                                                 log_bytes!(chan_id), action);
5033                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5034                                                 }
5035                                                 if !during_init {
5036                                                         let res = handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5037                                                                 peer_state, per_peer_state, chan);
5038                                                         if let Err(e) = res {
5039                                                                 // TODO: This is a *critical* error - we probably updated the outbound edge
5040                                                                 // of the HTLC's monitor with a preimage. We should retry this monitor
5041                                                                 // update over and over again until morale improves.
5042                                                                 log_error!(self.logger, "Failed to update channel monitor with preimage {:?}", payment_preimage);
5043                                                                 return Err((counterparty_node_id, e));
5044                                                         }
5045                                                 } else {
5046                                                         // If we're running during init we cannot update a monitor directly -
5047                                                         // they probably haven't actually been loaded yet. Instead, push the
5048                                                         // monitor update as a background event.
5049                                                         self.pending_background_events.lock().unwrap().push(
5050                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5051                                                                         counterparty_node_id,
5052                                                                         funding_txo: prev_hop.outpoint,
5053                                                                         update: monitor_update.clone(),
5054                                                                 });
5055                                                 }
5056                                         }
5057                                         return Ok(());
5058                                 }
5059                         }
5060                 }
5061                 let preimage_update = ChannelMonitorUpdate {
5062                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5063                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5064                                 payment_preimage,
5065                         }],
5066                 };
5067
5068                 if !during_init {
5069                         // We update the ChannelMonitor on the backward link, after
5070                         // receiving an `update_fulfill_htlc` from the forward link.
5071                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5072                         if update_res != ChannelMonitorUpdateStatus::Completed {
5073                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5074                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5075                                 // channel, or we must have an ability to receive the same event and try
5076                                 // again on restart.
5077                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5078                                         payment_preimage, update_res);
5079                         }
5080                 } else {
5081                         // If we're running during init we cannot update a monitor directly - they probably
5082                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5083                         // event.
5084                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5085                         // channel is already closed) we need to ultimately handle the monitor update
5086                         // completion action only after we've completed the monitor update. This is the only
5087                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5088                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5089                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5090                         // complete the monitor update completion action from `completion_action`.
5091                         self.pending_background_events.lock().unwrap().push(
5092                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5093                                         prev_hop.outpoint, preimage_update,
5094                                 )));
5095                 }
5096                 // Note that we do process the completion action here. This totally could be a
5097                 // duplicate claim, but we have no way of knowing without interrogating the
5098                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5099                 // generally always allowed to be duplicative (and it's specifically noted in
5100                 // `PaymentForwarded`).
5101                 self.handle_monitor_update_completion_actions(completion_action(None));
5102                 Ok(())
5103         }
5104
5105         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5106                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5107         }
5108
5109         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_id: [u8; 32]) {
5110                 match source {
5111                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5112                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5113                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5114                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage, session_priv, path, from_onchain, &self.pending_events, &self.logger);
5115                         },
5116                         HTLCSource::PreviousHopData(hop_data) => {
5117                                 let prev_outpoint = hop_data.outpoint;
5118                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5119                                         |htlc_claim_value_msat| {
5120                                                 if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5121                                                         let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5122                                                                 Some(claimed_htlc_value - forwarded_htlc_value)
5123                                                         } else { None };
5124
5125                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5126                                                                 event: events::Event::PaymentForwarded {
5127                                                                         fee_earned_msat,
5128                                                                         claim_from_onchain_tx: from_onchain,
5129                                                                         prev_channel_id: Some(prev_outpoint.to_channel_id()),
5130                                                                         next_channel_id: Some(next_channel_id),
5131                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5132                                                                 },
5133                                                                 downstream_counterparty_and_funding_outpoint: None,
5134                                                         })
5135                                                 } else { None }
5136                                         });
5137                                 if let Err((pk, err)) = res {
5138                                         let result: Result<(), _> = Err(err);
5139                                         let _ = handle_error!(self, result, pk);
5140                                 }
5141                         },
5142                 }
5143         }
5144
5145         /// Gets the node_id held by this ChannelManager
5146         pub fn get_our_node_id(&self) -> PublicKey {
5147                 self.our_network_pubkey.clone()
5148         }
5149
5150         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5151                 for action in actions.into_iter() {
5152                         match action {
5153                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5154                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5155                                         if let Some(ClaimingPayment {
5156                                                 amount_msat,
5157                                                 payment_purpose: purpose,
5158                                                 receiver_node_id,
5159                                                 htlcs,
5160                                                 sender_intended_value: sender_intended_total_msat,
5161                                         }) = payment {
5162                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5163                                                         payment_hash,
5164                                                         purpose,
5165                                                         amount_msat,
5166                                                         receiver_node_id: Some(receiver_node_id),
5167                                                         htlcs,
5168                                                         sender_intended_total_msat,
5169                                                 }, None));
5170                                         }
5171                                 },
5172                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5173                                         event, downstream_counterparty_and_funding_outpoint
5174                                 } => {
5175                                         self.pending_events.lock().unwrap().push_back((event, None));
5176                                         if let Some((node_id, funding_outpoint, blocker)) = downstream_counterparty_and_funding_outpoint {
5177                                                 self.handle_monitor_update_release(node_id, funding_outpoint, Some(blocker));
5178                                         }
5179                                 },
5180                         }
5181                 }
5182         }
5183
5184         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5185         /// update completion.
5186         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5187                 channel: &mut Channel<<SP::Target as SignerProvider>::Signer>, raa: Option<msgs::RevokeAndACK>,
5188                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5189                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5190                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5191         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
5192                 log_trace!(self.logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5193                         log_bytes!(channel.context.channel_id()),
5194                         if raa.is_some() { "an" } else { "no" },
5195                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5196                         if funding_broadcastable.is_some() { "" } else { "not " },
5197                         if channel_ready.is_some() { "sending" } else { "without" },
5198                         if announcement_sigs.is_some() { "sending" } else { "without" });
5199
5200                 let mut htlc_forwards = None;
5201
5202                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5203                 if !pending_forwards.is_empty() {
5204                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5205                                 channel.context.get_funding_txo().unwrap(), channel.context.get_user_id(), pending_forwards));
5206                 }
5207
5208                 if let Some(msg) = channel_ready {
5209                         send_channel_ready!(self, pending_msg_events, channel, msg);
5210                 }
5211                 if let Some(msg) = announcement_sigs {
5212                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5213                                 node_id: counterparty_node_id,
5214                                 msg,
5215                         });
5216                 }
5217
5218                 macro_rules! handle_cs { () => {
5219                         if let Some(update) = commitment_update {
5220                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5221                                         node_id: counterparty_node_id,
5222                                         updates: update,
5223                                 });
5224                         }
5225                 } }
5226                 macro_rules! handle_raa { () => {
5227                         if let Some(revoke_and_ack) = raa {
5228                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5229                                         node_id: counterparty_node_id,
5230                                         msg: revoke_and_ack,
5231                                 });
5232                         }
5233                 } }
5234                 match order {
5235                         RAACommitmentOrder::CommitmentFirst => {
5236                                 handle_cs!();
5237                                 handle_raa!();
5238                         },
5239                         RAACommitmentOrder::RevokeAndACKFirst => {
5240                                 handle_raa!();
5241                                 handle_cs!();
5242                         },
5243                 }
5244
5245                 if let Some(tx) = funding_broadcastable {
5246                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
5247                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5248                 }
5249
5250                 {
5251                         let mut pending_events = self.pending_events.lock().unwrap();
5252                         emit_channel_pending_event!(pending_events, channel);
5253                         emit_channel_ready_event!(pending_events, channel);
5254                 }
5255
5256                 htlc_forwards
5257         }
5258
5259         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5260                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5261
5262                 let counterparty_node_id = match counterparty_node_id {
5263                         Some(cp_id) => cp_id.clone(),
5264                         None => {
5265                                 // TODO: Once we can rely on the counterparty_node_id from the
5266                                 // monitor event, this and the id_to_peer map should be removed.
5267                                 let id_to_peer = self.id_to_peer.lock().unwrap();
5268                                 match id_to_peer.get(&funding_txo.to_channel_id()) {
5269                                         Some(cp_id) => cp_id.clone(),
5270                                         None => return,
5271                                 }
5272                         }
5273                 };
5274                 let per_peer_state = self.per_peer_state.read().unwrap();
5275                 let mut peer_state_lock;
5276                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5277                 if peer_state_mutex_opt.is_none() { return }
5278                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5279                 let peer_state = &mut *peer_state_lock;
5280                 let channel =
5281                         if let Some(chan) = peer_state.channel_by_id.get_mut(&funding_txo.to_channel_id()) {
5282                                 chan
5283                         } else {
5284                                 let update_actions = peer_state.monitor_update_blocked_actions
5285                                         .remove(&funding_txo.to_channel_id()).unwrap_or(Vec::new());
5286                                 mem::drop(peer_state_lock);
5287                                 mem::drop(per_peer_state);
5288                                 self.handle_monitor_update_completion_actions(update_actions);
5289                                 return;
5290                         };
5291                 let remaining_in_flight =
5292                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5293                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5294                                 pending.len()
5295                         } else { 0 };
5296                 log_trace!(self.logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5297                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5298                         remaining_in_flight);
5299                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5300                         return;
5301                 }
5302                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5303         }
5304
5305         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5306         ///
5307         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5308         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5309         /// the channel.
5310         ///
5311         /// The `user_channel_id` parameter will be provided back in
5312         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5313         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5314         ///
5315         /// Note that this method will return an error and reject the channel, if it requires support
5316         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
5317         /// used to accept such channels.
5318         ///
5319         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5320         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5321         pub fn accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
5322                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
5323         }
5324
5325         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
5326         /// it as confirmed immediately.
5327         ///
5328         /// The `user_channel_id` parameter will be provided back in
5329         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
5330         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
5331         ///
5332         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
5333         /// and (if the counterparty agrees), enables forwarding of payments immediately.
5334         ///
5335         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
5336         /// transaction and blindly assumes that it will eventually confirm.
5337         ///
5338         /// If it does not confirm before we decide to close the channel, or if the funding transaction
5339         /// does not pay to the correct script the correct amount, *you will lose funds*.
5340         ///
5341         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
5342         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
5343         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> {
5344                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
5345         }
5346
5347         fn do_accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
5348                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5349
5350                 let peers_without_funded_channels =
5351                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
5352                 let per_peer_state = self.per_peer_state.read().unwrap();
5353                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5354                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
5355                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5356                 let peer_state = &mut *peer_state_lock;
5357                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
5358
5359                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
5360                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
5361                 // that we can delay allocating the SCID until after we're sure that the checks below will
5362                 // succeed.
5363                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
5364                         Some(unaccepted_channel) => {
5365                                 let best_block_height = self.best_block.read().unwrap().height();
5366                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5367                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
5368                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
5369                                         &self.logger, accept_0conf).map_err(|e| APIError::ChannelUnavailable { err: e.to_string() })
5370                         }
5371                         _ => Err(APIError::APIMisuseError { err: "No such channel awaiting to be accepted.".to_owned() })
5372                 }?;
5373
5374                 if accept_0conf {
5375                         // This should have been correctly configured by the call to InboundV1Channel::new.
5376                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
5377                 } else if channel.context.get_channel_type().requires_zero_conf() {
5378                         let send_msg_err_event = events::MessageSendEvent::HandleError {
5379                                 node_id: channel.context.get_counterparty_node_id(),
5380                                 action: msgs::ErrorAction::SendErrorMessage{
5381                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
5382                                 }
5383                         };
5384                         peer_state.pending_msg_events.push(send_msg_err_event);
5385                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
5386                 } else {
5387                         // If this peer already has some channels, a new channel won't increase our number of peers
5388                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5389                         // channels per-peer we can accept channels from a peer with existing ones.
5390                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
5391                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
5392                                         node_id: channel.context.get_counterparty_node_id(),
5393                                         action: msgs::ErrorAction::SendErrorMessage{
5394                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
5395                                         }
5396                                 };
5397                                 peer_state.pending_msg_events.push(send_msg_err_event);
5398                                 return Err(APIError::APIMisuseError { err: "Too many peers with unfunded channels, refusing to accept new ones".to_owned() });
5399                         }
5400                 }
5401
5402                 // Now that we know we have a channel, assign an outbound SCID alias.
5403                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5404                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5405
5406                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5407                         node_id: channel.context.get_counterparty_node_id(),
5408                         msg: channel.accept_inbound_channel(),
5409                 });
5410
5411                 peer_state.inbound_v1_channel_by_id.insert(temporary_channel_id.clone(), channel);
5412
5413                 Ok(())
5414         }
5415
5416         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
5417         /// or 0-conf channels.
5418         ///
5419         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
5420         /// non-0-conf channels we have with the peer.
5421         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
5422         where Filter: Fn(&PeerState<<SP::Target as SignerProvider>::Signer>) -> bool {
5423                 let mut peers_without_funded_channels = 0;
5424                 let best_block_height = self.best_block.read().unwrap().height();
5425                 {
5426                         let peer_state_lock = self.per_peer_state.read().unwrap();
5427                         for (_, peer_mtx) in peer_state_lock.iter() {
5428                                 let peer = peer_mtx.lock().unwrap();
5429                                 if !maybe_count_peer(&*peer) { continue; }
5430                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
5431                                 if num_unfunded_channels == peer.total_channel_count() {
5432                                         peers_without_funded_channels += 1;
5433                                 }
5434                         }
5435                 }
5436                 return peers_without_funded_channels;
5437         }
5438
5439         fn unfunded_channel_count(
5440                 peer: &PeerState<<SP::Target as SignerProvider>::Signer>, best_block_height: u32
5441         ) -> usize {
5442                 let mut num_unfunded_channels = 0;
5443                 for (_, chan) in peer.channel_by_id.iter() {
5444                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
5445                         // which have not yet had any confirmations on-chain.
5446                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
5447                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
5448                         {
5449                                 num_unfunded_channels += 1;
5450                         }
5451                 }
5452                 for (_, chan) in peer.inbound_v1_channel_by_id.iter() {
5453                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
5454                                 num_unfunded_channels += 1;
5455                         }
5456                 }
5457                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
5458         }
5459
5460         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
5461                 if msg.chain_hash != self.genesis_hash {
5462                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
5463                 }
5464
5465                 if !self.default_configuration.accept_inbound_channels {
5466                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5467                 }
5468
5469                 // Get the number of peers with channels, but without funded ones. We don't care too much
5470                 // about peers that never open a channel, so we filter by peers that have at least one
5471                 // channel, and then limit the number of those with unfunded channels.
5472                 let channeled_peers_without_funding =
5473                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
5474
5475                 let per_peer_state = self.per_peer_state.read().unwrap();
5476                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5477                     .ok_or_else(|| {
5478                                 debug_assert!(false);
5479                                 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())
5480                         })?;
5481                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5482                 let peer_state = &mut *peer_state_lock;
5483
5484                 // If this peer already has some channels, a new channel won't increase our number of peers
5485                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
5486                 // channels per-peer we can accept channels from a peer with existing ones.
5487                 if peer_state.total_channel_count() == 0 &&
5488                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
5489                         !self.default_configuration.manually_accept_inbound_channels
5490                 {
5491                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5492                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
5493                                 msg.temporary_channel_id.clone()));
5494                 }
5495
5496                 let best_block_height = self.best_block.read().unwrap().height();
5497                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
5498                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
5499                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
5500                                 msg.temporary_channel_id.clone()));
5501                 }
5502
5503                 let channel_id = msg.temporary_channel_id;
5504                 let channel_exists = peer_state.has_channel(&channel_id);
5505                 if channel_exists {
5506                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
5507                 }
5508
5509                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
5510                 if self.default_configuration.manually_accept_inbound_channels {
5511                         let mut pending_events = self.pending_events.lock().unwrap();
5512                         pending_events.push_back((events::Event::OpenChannelRequest {
5513                                 temporary_channel_id: msg.temporary_channel_id.clone(),
5514                                 counterparty_node_id: counterparty_node_id.clone(),
5515                                 funding_satoshis: msg.funding_satoshis,
5516                                 push_msat: msg.push_msat,
5517                                 channel_type: msg.channel_type.clone().unwrap(),
5518                         }, None));
5519                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
5520                                 open_channel_msg: msg.clone(),
5521                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
5522                         });
5523                         return Ok(());
5524                 }
5525
5526                 // Otherwise create the channel right now.
5527                 let mut random_bytes = [0u8; 16];
5528                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
5529                 let user_channel_id = u128::from_be_bytes(random_bytes);
5530                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
5531                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
5532                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
5533                 {
5534                         Err(e) => {
5535                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
5536                         },
5537                         Ok(res) => res
5538                 };
5539
5540                 let channel_type = channel.context.get_channel_type();
5541                 if channel_type.requires_zero_conf() {
5542                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
5543                 }
5544                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
5545                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
5546                 }
5547
5548                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
5549                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
5550
5551                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
5552                         node_id: counterparty_node_id.clone(),
5553                         msg: channel.accept_inbound_channel(),
5554                 });
5555                 peer_state.inbound_v1_channel_by_id.insert(channel_id, channel);
5556                 Ok(())
5557         }
5558
5559         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
5560                 let (value, output_script, user_id) = {
5561                         let per_peer_state = self.per_peer_state.read().unwrap();
5562                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5563                                 .ok_or_else(|| {
5564                                         debug_assert!(false);
5565                                         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)
5566                                 })?;
5567                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5568                         let peer_state = &mut *peer_state_lock;
5569                         match peer_state.outbound_v1_channel_by_id.entry(msg.temporary_channel_id) {
5570                                 hash_map::Entry::Occupied(mut chan) => {
5571                                         try_v1_outbound_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), chan);
5572                                         (chan.get().context.get_value_satoshis(), chan.get().context.get_funding_redeemscript().to_v0_p2wsh(), chan.get().context.get_user_id())
5573                                 },
5574                                 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))
5575                         }
5576                 };
5577                 let mut pending_events = self.pending_events.lock().unwrap();
5578                 pending_events.push_back((events::Event::FundingGenerationReady {
5579                         temporary_channel_id: msg.temporary_channel_id,
5580                         counterparty_node_id: *counterparty_node_id,
5581                         channel_value_satoshis: value,
5582                         output_script,
5583                         user_channel_id: user_id,
5584                 }, None));
5585                 Ok(())
5586         }
5587
5588         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
5589                 let best_block = *self.best_block.read().unwrap();
5590
5591                 let per_peer_state = self.per_peer_state.read().unwrap();
5592                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5593                         .ok_or_else(|| {
5594                                 debug_assert!(false);
5595                                 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)
5596                         })?;
5597
5598                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5599                 let peer_state = &mut *peer_state_lock;
5600                 let (chan, funding_msg, monitor) =
5601                         match peer_state.inbound_v1_channel_by_id.remove(&msg.temporary_channel_id) {
5602                                 Some(inbound_chan) => {
5603                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &self.logger) {
5604                                                 Ok(res) => res,
5605                                                 Err((mut inbound_chan, err)) => {
5606                                                         // We've already removed this inbound channel from the map in `PeerState`
5607                                                         // above so at this point we just need to clean up any lingering entries
5608                                                         // concerning this channel as it is safe to do so.
5609                                                         update_maps_on_chan_removal!(self, &inbound_chan.context);
5610                                                         let user_id = inbound_chan.context.get_user_id();
5611                                                         let shutdown_res = inbound_chan.context.force_shutdown(false);
5612                                                         return Err(MsgHandleErrInternal::from_finish_shutdown(format!("{}", err),
5613                                                                 msg.temporary_channel_id, user_id, shutdown_res, None, inbound_chan.context.get_value_satoshis()));
5614                                                 },
5615                                         }
5616                                 },
5617                                 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))
5618                         };
5619
5620                 match peer_state.channel_by_id.entry(funding_msg.channel_id) {
5621                         hash_map::Entry::Occupied(_) => {
5622                                 Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
5623                         },
5624                         hash_map::Entry::Vacant(e) => {
5625                                 match self.id_to_peer.lock().unwrap().entry(chan.context.channel_id()) {
5626                                         hash_map::Entry::Occupied(_) => {
5627                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
5628                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
5629                                                         funding_msg.channel_id))
5630                                         },
5631                                         hash_map::Entry::Vacant(i_e) => {
5632                                                 i_e.insert(chan.context.get_counterparty_node_id());
5633                                         }
5634                                 }
5635
5636                                 // There's no problem signing a counterparty's funding transaction if our monitor
5637                                 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
5638                                 // accepted payment from yet. We do, however, need to wait to send our channel_ready
5639                                 // until we have persisted our monitor.
5640                                 let new_channel_id = funding_msg.channel_id;
5641                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
5642                                         node_id: counterparty_node_id.clone(),
5643                                         msg: funding_msg,
5644                                 });
5645
5646                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
5647
5648                                 let chan = e.insert(chan);
5649                                 let mut res = handle_new_monitor_update!(self, monitor_res, peer_state_lock, peer_state,
5650                                         per_peer_state, chan, MANUALLY_REMOVING_INITIAL_MONITOR,
5651                                         { peer_state.channel_by_id.remove(&new_channel_id) });
5652
5653                                 // Note that we reply with the new channel_id in error messages if we gave up on the
5654                                 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
5655                                 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
5656                                 // any messages referencing a previously-closed channel anyway.
5657                                 // We do not propagate the monitor update to the user as it would be for a monitor
5658                                 // that we didn't manage to store (and that we don't care about - we don't respond
5659                                 // with the funding_signed so the channel can never go on chain).
5660                                 if let Err(MsgHandleErrInternal { shutdown_finish: Some((res, _)), .. }) = &mut res {
5661                                         res.0 = None;
5662                                 }
5663                                 res.map(|_| ())
5664                         }
5665                 }
5666         }
5667
5668         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
5669                 let best_block = *self.best_block.read().unwrap();
5670                 let per_peer_state = self.per_peer_state.read().unwrap();
5671                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5672                         .ok_or_else(|| {
5673                                 debug_assert!(false);
5674                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5675                         })?;
5676
5677                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5678                 let peer_state = &mut *peer_state_lock;
5679                 match peer_state.channel_by_id.entry(msg.channel_id) {
5680                         hash_map::Entry::Occupied(mut chan) => {
5681                                 let monitor = try_chan_entry!(self,
5682                                         chan.get_mut().funding_signed(&msg, best_block, &self.signer_provider, &self.logger), chan);
5683                                 let update_res = self.chain_monitor.watch_channel(chan.get().context.get_funding_txo().unwrap(), monitor);
5684                                 let mut res = handle_new_monitor_update!(self, update_res, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
5685                                 if let Err(MsgHandleErrInternal { ref mut shutdown_finish, .. }) = res {
5686                                         // We weren't able to watch the channel to begin with, so no updates should be made on
5687                                         // it. Previously, full_stack_target found an (unreachable) panic when the
5688                                         // monitor update contained within `shutdown_finish` was applied.
5689                                         if let Some((ref mut shutdown_finish, _)) = shutdown_finish {
5690                                                 shutdown_finish.0.take();
5691                                         }
5692                                 }
5693                                 res.map(|_| ())
5694                         },
5695                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
5696                 }
5697         }
5698
5699         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
5700                 let per_peer_state = self.per_peer_state.read().unwrap();
5701                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5702                         .ok_or_else(|| {
5703                                 debug_assert!(false);
5704                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5705                         })?;
5706                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5707                 let peer_state = &mut *peer_state_lock;
5708                 match peer_state.channel_by_id.entry(msg.channel_id) {
5709                         hash_map::Entry::Occupied(mut chan) => {
5710                                 let announcement_sigs_opt = try_chan_entry!(self, chan.get_mut().channel_ready(&msg, &self.node_signer,
5711                                         self.genesis_hash.clone(), &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan);
5712                                 if let Some(announcement_sigs) = announcement_sigs_opt {
5713                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(chan.get().context.channel_id()));
5714                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5715                                                 node_id: counterparty_node_id.clone(),
5716                                                 msg: announcement_sigs,
5717                                         });
5718                                 } else if chan.get().context.is_usable() {
5719                                         // If we're sending an announcement_signatures, we'll send the (public)
5720                                         // channel_update after sending a channel_announcement when we receive our
5721                                         // counterparty's announcement_signatures. Thus, we only bother to send a
5722                                         // channel_update here if the channel is not public, i.e. we're not sending an
5723                                         // announcement_signatures.
5724                                         log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", log_bytes!(chan.get().context.channel_id()));
5725                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
5726                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
5727                                                         node_id: counterparty_node_id.clone(),
5728                                                         msg,
5729                                                 });
5730                                         }
5731                                 }
5732
5733                                 {
5734                                         let mut pending_events = self.pending_events.lock().unwrap();
5735                                         emit_channel_ready_event!(pending_events, chan.get_mut());
5736                                 }
5737
5738                                 Ok(())
5739                         },
5740                         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))
5741                 }
5742         }
5743
5744         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
5745                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)>;
5746                 let result: Result<(), _> = loop {
5747                         let per_peer_state = self.per_peer_state.read().unwrap();
5748                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5749                                 .ok_or_else(|| {
5750                                         debug_assert!(false);
5751                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5752                                 })?;
5753                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5754                         let peer_state = &mut *peer_state_lock;
5755                         // TODO(dunxen): Fix this duplication when we switch to a single map with enums as per
5756                         // https://github.com/lightningdevkit/rust-lightning/issues/2422
5757                         if let hash_map::Entry::Occupied(chan_entry) = peer_state.outbound_v1_channel_by_id.entry(msg.channel_id.clone()) {
5758                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", log_bytes!(&msg.channel_id[..]));
5759                                 self.issue_channel_close_events(&chan_entry.get().context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
5760                                 let mut chan = remove_channel!(self, chan_entry);
5761                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
5762                                 return Ok(());
5763                         } else if let hash_map::Entry::Occupied(chan_entry) = peer_state.inbound_v1_channel_by_id.entry(msg.channel_id.clone()) {
5764                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", log_bytes!(&msg.channel_id[..]));
5765                                 self.issue_channel_close_events(&chan_entry.get().context, ClosureReason::CounterpartyCoopClosedUnfundedChannel);
5766                                 let mut chan = remove_channel!(self, chan_entry);
5767                                 self.finish_force_close_channel(chan.context.force_shutdown(false));
5768                                 return Ok(());
5769                         } else if let hash_map::Entry::Occupied(mut chan_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
5770                                 if !chan_entry.get().received_shutdown() {
5771                                         log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
5772                                                 log_bytes!(msg.channel_id),
5773                                                 if chan_entry.get().sent_shutdown() { " after we initiated shutdown" } else { "" });
5774                                 }
5775
5776                                 let funding_txo_opt = chan_entry.get().context.get_funding_txo();
5777                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_entry!(self,
5778                                         chan_entry.get_mut().shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_entry);
5779                                 dropped_htlcs = htlcs;
5780
5781                                 if let Some(msg) = shutdown {
5782                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
5783                                         // here as we don't need the monitor update to complete until we send a
5784                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
5785                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
5786                                                 node_id: *counterparty_node_id,
5787                                                 msg,
5788                                         });
5789                                 }
5790
5791                                 // Update the monitor with the shutdown script if necessary.
5792                                 if let Some(monitor_update) = monitor_update_opt {
5793                                         break handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
5794                                                 peer_state_lock, peer_state, per_peer_state, chan_entry).map(|_| ());
5795                                 }
5796                                 break Ok(());
5797                         } else {
5798                                 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))
5799                         }
5800                 };
5801                 for htlc_source in dropped_htlcs.drain(..) {
5802                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
5803                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
5804                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
5805                 }
5806
5807                 result
5808         }
5809
5810         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
5811                 let per_peer_state = self.per_peer_state.read().unwrap();
5812                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5813                         .ok_or_else(|| {
5814                                 debug_assert!(false);
5815                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5816                         })?;
5817                 let (tx, chan_option) = {
5818                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5819                         let peer_state = &mut *peer_state_lock;
5820                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
5821                                 hash_map::Entry::Occupied(mut chan_entry) => {
5822                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), chan_entry);
5823                                         if let Some(msg) = closing_signed {
5824                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
5825                                                         node_id: counterparty_node_id.clone(),
5826                                                         msg,
5827                                                 });
5828                                         }
5829                                         if tx.is_some() {
5830                                                 // We're done with this channel, we've got a signed closing transaction and
5831                                                 // will send the closing_signed back to the remote peer upon return. This
5832                                                 // also implies there are no pending HTLCs left on the channel, so we can
5833                                                 // fully delete it from tracking (the channel monitor is still around to
5834                                                 // watch for old state broadcasts)!
5835                                                 (tx, Some(remove_channel!(self, chan_entry)))
5836                                         } else { (tx, None) }
5837                                 },
5838                                 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))
5839                         }
5840                 };
5841                 if let Some(broadcast_tx) = tx {
5842                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
5843                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
5844                 }
5845                 if let Some(chan) = chan_option {
5846                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5847                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5848                                 let peer_state = &mut *peer_state_lock;
5849                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5850                                         msg: update
5851                                 });
5852                         }
5853                         self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
5854                 }
5855                 Ok(())
5856         }
5857
5858         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
5859                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
5860                 //determine the state of the payment based on our response/if we forward anything/the time
5861                 //we take to respond. We should take care to avoid allowing such an attack.
5862                 //
5863                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
5864                 //us repeatedly garbled in different ways, and compare our error messages, which are
5865                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
5866                 //but we should prevent it anyway.
5867
5868                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg);
5869                 let per_peer_state = self.per_peer_state.read().unwrap();
5870                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5871                         .ok_or_else(|| {
5872                                 debug_assert!(false);
5873                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5874                         })?;
5875                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5876                 let peer_state = &mut *peer_state_lock;
5877                 match peer_state.channel_by_id.entry(msg.channel_id) {
5878                         hash_map::Entry::Occupied(mut chan) => {
5879
5880                                 let pending_forward_info = match decoded_hop_res {
5881                                         Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
5882                                                 self.construct_pending_htlc_status(msg, shared_secret, next_hop,
5883                                                         chan.get().context.config().accept_underpaying_htlcs, next_packet_pk_opt),
5884                                         Err(e) => PendingHTLCStatus::Fail(e)
5885                                 };
5886                                 let create_pending_htlc_status = |chan: &Channel<<SP::Target as SignerProvider>::Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
5887                                         // If the update_add is completely bogus, the call will Err and we will close,
5888                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
5889                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
5890                                         match pending_forward_info {
5891                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
5892                                                         let reason = if (error_code & 0x1000) != 0 {
5893                                                                 let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
5894                                                                 HTLCFailReason::reason(real_code, error_data)
5895                                                         } else {
5896                                                                 HTLCFailReason::from_failure_code(error_code)
5897                                                         }.get_encrypted_failure_packet(incoming_shared_secret, &None);
5898                                                         let msg = msgs::UpdateFailHTLC {
5899                                                                 channel_id: msg.channel_id,
5900                                                                 htlc_id: msg.htlc_id,
5901                                                                 reason
5902                                                         };
5903                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
5904                                                 },
5905                                                 _ => pending_forward_info
5906                                         }
5907                                 };
5908                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &self.logger), chan);
5909                         },
5910                         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))
5911                 }
5912                 Ok(())
5913         }
5914
5915         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
5916                 let (htlc_source, forwarded_htlc_value) = {
5917                         let per_peer_state = self.per_peer_state.read().unwrap();
5918                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5919                                 .ok_or_else(|| {
5920                                         debug_assert!(false);
5921                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5922                                 })?;
5923                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5924                         let peer_state = &mut *peer_state_lock;
5925                         match peer_state.channel_by_id.entry(msg.channel_id) {
5926                                 hash_map::Entry::Occupied(mut chan) => {
5927                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), chan)
5928                                 },
5929                                 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))
5930                         }
5931                 };
5932                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, msg.channel_id);
5933                 Ok(())
5934         }
5935
5936         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
5937                 let per_peer_state = self.per_peer_state.read().unwrap();
5938                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5939                         .ok_or_else(|| {
5940                                 debug_assert!(false);
5941                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5942                         })?;
5943                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5944                 let peer_state = &mut *peer_state_lock;
5945                 match peer_state.channel_by_id.entry(msg.channel_id) {
5946                         hash_map::Entry::Occupied(mut chan) => {
5947                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan);
5948                         },
5949                         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))
5950                 }
5951                 Ok(())
5952         }
5953
5954         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
5955                 let per_peer_state = self.per_peer_state.read().unwrap();
5956                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5957                         .ok_or_else(|| {
5958                                 debug_assert!(false);
5959                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5960                         })?;
5961                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5962                 let peer_state = &mut *peer_state_lock;
5963                 match peer_state.channel_by_id.entry(msg.channel_id) {
5964                         hash_map::Entry::Occupied(mut chan) => {
5965                                 if (msg.failure_code & 0x8000) == 0 {
5966                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
5967                                         try_chan_entry!(self, Err(chan_err), chan);
5968                                 }
5969                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan);
5970                                 Ok(())
5971                         },
5972                         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))
5973                 }
5974         }
5975
5976         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
5977                 let per_peer_state = self.per_peer_state.read().unwrap();
5978                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
5979                         .ok_or_else(|| {
5980                                 debug_assert!(false);
5981                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
5982                         })?;
5983                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5984                 let peer_state = &mut *peer_state_lock;
5985                 match peer_state.channel_by_id.entry(msg.channel_id) {
5986                         hash_map::Entry::Occupied(mut chan) => {
5987                                 let funding_txo = chan.get().context.get_funding_txo();
5988                                 let monitor_update_opt = try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &self.logger), chan);
5989                                 if let Some(monitor_update) = monitor_update_opt {
5990                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
5991                                                 peer_state, per_peer_state, chan).map(|_| ())
5992                                 } else { Ok(()) }
5993                         },
5994                         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))
5995                 }
5996         }
5997
5998         #[inline]
5999         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6000                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6001                         let mut push_forward_event = false;
6002                         let mut new_intercept_events = VecDeque::new();
6003                         let mut failed_intercept_forwards = Vec::new();
6004                         if !pending_forwards.is_empty() {
6005                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6006                                         let scid = match forward_info.routing {
6007                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6008                                                 PendingHTLCRouting::Receive { .. } => 0,
6009                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6010                                         };
6011                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6012                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6013
6014                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6015                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6016                                         match forward_htlcs.entry(scid) {
6017                                                 hash_map::Entry::Occupied(mut entry) => {
6018                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6019                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
6020                                                 },
6021                                                 hash_map::Entry::Vacant(entry) => {
6022                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6023                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.genesis_hash)
6024                                                         {
6025                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
6026                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6027                                                                 match pending_intercepts.entry(intercept_id) {
6028                                                                         hash_map::Entry::Vacant(entry) => {
6029                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6030                                                                                         requested_next_hop_scid: scid,
6031                                                                                         payment_hash: forward_info.payment_hash,
6032                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6033                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6034                                                                                         intercept_id
6035                                                                                 }, None));
6036                                                                                 entry.insert(PendingAddHTLCInfo {
6037                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
6038                                                                         },
6039                                                                         hash_map::Entry::Occupied(_) => {
6040                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6041                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6042                                                                                         short_channel_id: prev_short_channel_id,
6043                                                                                         user_channel_id: Some(prev_user_channel_id),
6044                                                                                         outpoint: prev_funding_outpoint,
6045                                                                                         htlc_id: prev_htlc_id,
6046                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6047                                                                                         phantom_shared_secret: None,
6048                                                                                 });
6049
6050                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6051                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6052                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6053                                                                                 ));
6054                                                                         }
6055                                                                 }
6056                                                         } else {
6057                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6058                                                                 // payments are being processed.
6059                                                                 if forward_htlcs_empty {
6060                                                                         push_forward_event = true;
6061                                                                 }
6062                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6063                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
6064                                                         }
6065                                                 }
6066                                         }
6067                                 }
6068                         }
6069
6070                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6071                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6072                         }
6073
6074                         if !new_intercept_events.is_empty() {
6075                                 let mut events = self.pending_events.lock().unwrap();
6076                                 events.append(&mut new_intercept_events);
6077                         }
6078                         if push_forward_event { self.push_pending_forwards_ev() }
6079                 }
6080         }
6081
6082         fn push_pending_forwards_ev(&self) {
6083                 let mut pending_events = self.pending_events.lock().unwrap();
6084                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6085                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6086                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6087                 ).count();
6088                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6089                 // events is done in batches and they are not removed until we're done processing each
6090                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6091                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6092                 // payments will need an additional forwarding event before being claimed to make them look
6093                 // real by taking more time.
6094                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6095                         pending_events.push_back((Event::PendingHTLCsForwardable {
6096                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6097                         }, None));
6098                 }
6099         }
6100
6101         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6102         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6103         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6104         /// the [`ChannelMonitorUpdate`] in question.
6105         fn raa_monitor_updates_held(&self,
6106                 actions_blocking_raa_monitor_updates: &BTreeMap<[u8; 32], Vec<RAAMonitorUpdateBlockingAction>>,
6107                 channel_funding_outpoint: OutPoint, counterparty_node_id: PublicKey
6108         ) -> bool {
6109                 actions_blocking_raa_monitor_updates
6110                         .get(&channel_funding_outpoint.to_channel_id()).map(|v| !v.is_empty()).unwrap_or(false)
6111                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6112                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6113                                 channel_funding_outpoint,
6114                                 counterparty_node_id,
6115                         })
6116                 })
6117         }
6118
6119         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
6120                 let (htlcs_to_fail, res) = {
6121                         let per_peer_state = self.per_peer_state.read().unwrap();
6122                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
6123                                 .ok_or_else(|| {
6124                                         debug_assert!(false);
6125                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6126                                 }).map(|mtx| mtx.lock().unwrap())?;
6127                         let peer_state = &mut *peer_state_lock;
6128                         match peer_state.channel_by_id.entry(msg.channel_id) {
6129                                 hash_map::Entry::Occupied(mut chan) => {
6130                                         let funding_txo = chan.get().context.get_funding_txo();
6131                                         let (htlcs_to_fail, monitor_update_opt) = try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), chan);
6132                                         let res = if let Some(monitor_update) = monitor_update_opt {
6133                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
6134                                                         peer_state_lock, peer_state, per_peer_state, chan).map(|_| ())
6135                                         } else { Ok(()) };
6136                                         (htlcs_to_fail, res)
6137                                 },
6138                                 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))
6139                         }
6140                 };
6141                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
6142                 res
6143         }
6144
6145         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
6146                 let per_peer_state = self.per_peer_state.read().unwrap();
6147                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6148                         .ok_or_else(|| {
6149                                 debug_assert!(false);
6150                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6151                         })?;
6152                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6153                 let peer_state = &mut *peer_state_lock;
6154                 match peer_state.channel_by_id.entry(msg.channel_id) {
6155                         hash_map::Entry::Occupied(mut chan) => {
6156                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg, &self.logger), chan);
6157                         },
6158                         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))
6159                 }
6160                 Ok(())
6161         }
6162
6163         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
6164                 let per_peer_state = self.per_peer_state.read().unwrap();
6165                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6166                         .ok_or_else(|| {
6167                                 debug_assert!(false);
6168                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6169                         })?;
6170                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6171                 let peer_state = &mut *peer_state_lock;
6172                 match peer_state.channel_by_id.entry(msg.channel_id) {
6173                         hash_map::Entry::Occupied(mut chan) => {
6174                                 if !chan.get().context.is_usable() {
6175                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
6176                                 }
6177
6178                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
6179                                         msg: try_chan_entry!(self, chan.get_mut().announcement_signatures(
6180                                                 &self.node_signer, self.genesis_hash.clone(), self.best_block.read().unwrap().height(),
6181                                                 msg, &self.default_configuration
6182                                         ), chan),
6183                                         // Note that announcement_signatures fails if the channel cannot be announced,
6184                                         // so get_channel_update_for_broadcast will never fail by the time we get here.
6185                                         update_msg: Some(self.get_channel_update_for_broadcast(chan.get()).unwrap()),
6186                                 });
6187                         },
6188                         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))
6189                 }
6190                 Ok(())
6191         }
6192
6193         /// Returns ShouldPersist if anything changed, otherwise either SkipPersist or an Err.
6194         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
6195                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
6196                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
6197                         None => {
6198                                 // It's not a local channel
6199                                 return Ok(NotifyOption::SkipPersist)
6200                         }
6201                 };
6202                 let per_peer_state = self.per_peer_state.read().unwrap();
6203                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
6204                 if peer_state_mutex_opt.is_none() {
6205                         return Ok(NotifyOption::SkipPersist)
6206                 }
6207                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6208                 let peer_state = &mut *peer_state_lock;
6209                 match peer_state.channel_by_id.entry(chan_id) {
6210                         hash_map::Entry::Occupied(mut chan) => {
6211                                 if chan.get().context.get_counterparty_node_id() != *counterparty_node_id {
6212                                         if chan.get().context.should_announce() {
6213                                                 // If the announcement is about a channel of ours which is public, some
6214                                                 // other peer may simply be forwarding all its gossip to us. Don't provide
6215                                                 // a scary-looking error message and return Ok instead.
6216                                                 return Ok(NotifyOption::SkipPersist);
6217                                         }
6218                                         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));
6219                                 }
6220                                 let were_node_one = self.get_our_node_id().serialize()[..] < chan.get().context.get_counterparty_node_id().serialize()[..];
6221                                 let msg_from_node_one = msg.contents.flags & 1 == 0;
6222                                 if were_node_one == msg_from_node_one {
6223                                         return Ok(NotifyOption::SkipPersist);
6224                                 } else {
6225                                         log_debug!(self.logger, "Received channel_update for channel {}.", log_bytes!(chan_id));
6226                                         try_chan_entry!(self, chan.get_mut().channel_update(&msg), chan);
6227                                 }
6228                         },
6229                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersist)
6230                 }
6231                 Ok(NotifyOption::DoPersist)
6232         }
6233
6234         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
6235                 let htlc_forwards;
6236                 let need_lnd_workaround = {
6237                         let per_peer_state = self.per_peer_state.read().unwrap();
6238
6239                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6240                                 .ok_or_else(|| {
6241                                         debug_assert!(false);
6242                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6243                                 })?;
6244                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6245                         let peer_state = &mut *peer_state_lock;
6246                         match peer_state.channel_by_id.entry(msg.channel_id) {
6247                                 hash_map::Entry::Occupied(mut chan) => {
6248                                         // Currently, we expect all holding cell update_adds to be dropped on peer
6249                                         // disconnect, so Channel's reestablish will never hand us any holding cell
6250                                         // freed HTLCs to fail backwards. If in the future we no longer drop pending
6251                                         // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
6252                                         let responses = try_chan_entry!(self, chan.get_mut().channel_reestablish(
6253                                                 msg, &self.logger, &self.node_signer, self.genesis_hash,
6254                                                 &self.default_configuration, &*self.best_block.read().unwrap()), chan);
6255                                         let mut channel_update = None;
6256                                         if let Some(msg) = responses.shutdown_msg {
6257                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6258                                                         node_id: counterparty_node_id.clone(),
6259                                                         msg,
6260                                                 });
6261                                         } else if chan.get().context.is_usable() {
6262                                                 // If the channel is in a usable state (ie the channel is not being shut
6263                                                 // down), send a unicast channel_update to our counterparty to make sure
6264                                                 // they have the latest channel parameters.
6265                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
6266                                                         channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
6267                                                                 node_id: chan.get().context.get_counterparty_node_id(),
6268                                                                 msg,
6269                                                         });
6270                                                 }
6271                                         }
6272                                         let need_lnd_workaround = chan.get_mut().context.workaround_lnd_bug_4006.take();
6273                                         htlc_forwards = self.handle_channel_resumption(
6274                                                 &mut peer_state.pending_msg_events, chan.get_mut(), responses.raa, responses.commitment_update, responses.order,
6275                                                 Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
6276                                         if let Some(upd) = channel_update {
6277                                                 peer_state.pending_msg_events.push(upd);
6278                                         }
6279                                         need_lnd_workaround
6280                                 },
6281                                 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))
6282                         }
6283                 };
6284
6285                 if let Some(forwards) = htlc_forwards {
6286                         self.forward_htlcs(&mut [forwards][..]);
6287                 }
6288
6289                 if let Some(channel_ready_msg) = need_lnd_workaround {
6290                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
6291                 }
6292                 Ok(())
6293         }
6294
6295         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
6296         fn process_pending_monitor_events(&self) -> bool {
6297                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
6298
6299                 let mut failed_channels = Vec::new();
6300                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
6301                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
6302                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
6303                         for monitor_event in monitor_events.drain(..) {
6304                                 match monitor_event {
6305                                         MonitorEvent::HTLCEvent(htlc_update) => {
6306                                                 if let Some(preimage) = htlc_update.payment_preimage {
6307                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
6308                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, funding_outpoint.to_channel_id());
6309                                                 } else {
6310                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
6311                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
6312                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6313                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
6314                                                 }
6315                                         },
6316                                         MonitorEvent::CommitmentTxConfirmed(funding_outpoint) |
6317                                         MonitorEvent::UpdateFailed(funding_outpoint) => {
6318                                                 let counterparty_node_id_opt = match counterparty_node_id {
6319                                                         Some(cp_id) => Some(cp_id),
6320                                                         None => {
6321                                                                 // TODO: Once we can rely on the counterparty_node_id from the
6322                                                                 // monitor event, this and the id_to_peer map should be removed.
6323                                                                 let id_to_peer = self.id_to_peer.lock().unwrap();
6324                                                                 id_to_peer.get(&funding_outpoint.to_channel_id()).cloned()
6325                                                         }
6326                                                 };
6327                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
6328                                                         let per_peer_state = self.per_peer_state.read().unwrap();
6329                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
6330                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6331                                                                 let peer_state = &mut *peer_state_lock;
6332                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6333                                                                 if let hash_map::Entry::Occupied(chan_entry) = peer_state.channel_by_id.entry(funding_outpoint.to_channel_id()) {
6334                                                                         let mut chan = remove_channel!(self, chan_entry);
6335                                                                         failed_channels.push(chan.context.force_shutdown(false));
6336                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6337                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6338                                                                                         msg: update
6339                                                                                 });
6340                                                                         }
6341                                                                         let reason = if let MonitorEvent::UpdateFailed(_) = monitor_event {
6342                                                                                 ClosureReason::ProcessingError { err: "Failed to persist ChannelMonitor update during chain sync".to_string() }
6343                                                                         } else {
6344                                                                                 ClosureReason::CommitmentTxConfirmed
6345                                                                         };
6346                                                                         self.issue_channel_close_events(&chan.context, reason);
6347                                                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
6348                                                                                 node_id: chan.context.get_counterparty_node_id(),
6349                                                                                 action: msgs::ErrorAction::SendErrorMessage {
6350                                                                                         msg: msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() }
6351                                                                                 },
6352                                                                         });
6353                                                                 }
6354                                                         }
6355                                                 }
6356                                         },
6357                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
6358                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id, counterparty_node_id.as_ref());
6359                                         },
6360                                 }
6361                         }
6362                 }
6363
6364                 for failure in failed_channels.drain(..) {
6365                         self.finish_force_close_channel(failure);
6366                 }
6367
6368                 has_pending_monitor_events
6369         }
6370
6371         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
6372         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
6373         /// update events as a separate process method here.
6374         #[cfg(fuzzing)]
6375         pub fn process_monitor_events(&self) {
6376                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6377                 self.process_pending_monitor_events();
6378         }
6379
6380         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
6381         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
6382         /// update was applied.
6383         fn check_free_holding_cells(&self) -> bool {
6384                 let mut has_monitor_update = false;
6385                 let mut failed_htlcs = Vec::new();
6386                 let mut handle_errors = Vec::new();
6387
6388                 // Walk our list of channels and find any that need to update. Note that when we do find an
6389                 // update, if it includes actions that must be taken afterwards, we have to drop the
6390                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
6391                 // manage to go through all our peers without finding a single channel to update.
6392                 'peer_loop: loop {
6393                         let per_peer_state = self.per_peer_state.read().unwrap();
6394                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6395                                 'chan_loop: loop {
6396                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6397                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
6398                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut() {
6399                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
6400                                                 let funding_txo = chan.context.get_funding_txo();
6401                                                 let (monitor_opt, holding_cell_failed_htlcs) =
6402                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &self.logger);
6403                                                 if !holding_cell_failed_htlcs.is_empty() {
6404                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
6405                                                 }
6406                                                 if let Some(monitor_update) = monitor_opt {
6407                                                         has_monitor_update = true;
6408
6409                                                         let channel_id: [u8; 32] = *channel_id;
6410                                                         let res = handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
6411                                                                 peer_state_lock, peer_state, per_peer_state, chan, MANUALLY_REMOVING,
6412                                                                 peer_state.channel_by_id.remove(&channel_id));
6413                                                         if res.is_err() {
6414                                                                 handle_errors.push((counterparty_node_id, res));
6415                                                         }
6416                                                         continue 'peer_loop;
6417                                                 }
6418                                         }
6419                                         break 'chan_loop;
6420                                 }
6421                         }
6422                         break 'peer_loop;
6423                 }
6424
6425                 let has_update = has_monitor_update || !failed_htlcs.is_empty() || !handle_errors.is_empty();
6426                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
6427                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
6428                 }
6429
6430                 for (counterparty_node_id, err) in handle_errors.drain(..) {
6431                         let _ = handle_error!(self, err, counterparty_node_id);
6432                 }
6433
6434                 has_update
6435         }
6436
6437         /// Check whether any channels have finished removing all pending updates after a shutdown
6438         /// exchange and can now send a closing_signed.
6439         /// Returns whether any closing_signed messages were generated.
6440         fn maybe_generate_initial_closing_signed(&self) -> bool {
6441                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
6442                 let mut has_update = false;
6443                 {
6444                         let per_peer_state = self.per_peer_state.read().unwrap();
6445
6446                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6447                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6448                                 let peer_state = &mut *peer_state_lock;
6449                                 let pending_msg_events = &mut peer_state.pending_msg_events;
6450                                 peer_state.channel_by_id.retain(|channel_id, chan| {
6451                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
6452                                                 Ok((msg_opt, tx_opt)) => {
6453                                                         if let Some(msg) = msg_opt {
6454                                                                 has_update = true;
6455                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6456                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
6457                                                                 });
6458                                                         }
6459                                                         if let Some(tx) = tx_opt {
6460                                                                 // We're done with this channel. We got a closing_signed and sent back
6461                                                                 // a closing_signed with a closing transaction to broadcast.
6462                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6463                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6464                                                                                 msg: update
6465                                                                         });
6466                                                                 }
6467
6468                                                                 self.issue_channel_close_events(&chan.context, ClosureReason::CooperativeClosure);
6469
6470                                                                 log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
6471                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
6472                                                                 update_maps_on_chan_removal!(self, &chan.context);
6473                                                                 false
6474                                                         } else { true }
6475                                                 },
6476                                                 Err(e) => {
6477                                                         has_update = true;
6478                                                         let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
6479                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
6480                                                         !close_channel
6481                                                 }
6482                                         }
6483                                 });
6484                         }
6485                 }
6486
6487                 for (counterparty_node_id, err) in handle_errors.drain(..) {
6488                         let _ = handle_error!(self, err, counterparty_node_id);
6489                 }
6490
6491                 has_update
6492         }
6493
6494         /// Handle a list of channel failures during a block_connected or block_disconnected call,
6495         /// pushing the channel monitor update (if any) to the background events queue and removing the
6496         /// Channel object.
6497         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
6498                 for mut failure in failed_channels.drain(..) {
6499                         // Either a commitment transactions has been confirmed on-chain or
6500                         // Channel::block_disconnected detected that the funding transaction has been
6501                         // reorganized out of the main chain.
6502                         // We cannot broadcast our latest local state via monitor update (as
6503                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
6504                         // so we track the update internally and handle it when the user next calls
6505                         // timer_tick_occurred, guaranteeing we're running normally.
6506                         if let Some((counterparty_node_id, funding_txo, update)) = failure.0.take() {
6507                                 assert_eq!(update.updates.len(), 1);
6508                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
6509                                         assert!(should_broadcast);
6510                                 } else { unreachable!(); }
6511                                 self.pending_background_events.lock().unwrap().push(
6512                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
6513                                                 counterparty_node_id, funding_txo, update
6514                                         });
6515                         }
6516                         self.finish_force_close_channel(failure);
6517                 }
6518         }
6519
6520         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
6521         /// to pay us.
6522         ///
6523         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
6524         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
6525         ///
6526         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
6527         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
6528         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
6529         /// passed directly to [`claim_funds`].
6530         ///
6531         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
6532         ///
6533         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
6534         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
6535         ///
6536         /// # Note
6537         ///
6538         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
6539         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
6540         ///
6541         /// Errors if `min_value_msat` is greater than total bitcoin supply.
6542         ///
6543         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
6544         /// on versions of LDK prior to 0.0.114.
6545         ///
6546         /// [`claim_funds`]: Self::claim_funds
6547         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
6548         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
6549         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
6550         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
6551         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
6552         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
6553                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
6554                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
6555                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
6556                         min_final_cltv_expiry_delta)
6557         }
6558
6559         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
6560         /// stored external to LDK.
6561         ///
6562         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
6563         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
6564         /// the `min_value_msat` provided here, if one is provided.
6565         ///
6566         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
6567         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
6568         /// payments.
6569         ///
6570         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
6571         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
6572         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
6573         /// sender "proof-of-payment" unless they have paid the required amount.
6574         ///
6575         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
6576         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
6577         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
6578         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
6579         /// invoices when no timeout is set.
6580         ///
6581         /// Note that we use block header time to time-out pending inbound payments (with some margin
6582         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
6583         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
6584         /// If you need exact expiry semantics, you should enforce them upon receipt of
6585         /// [`PaymentClaimable`].
6586         ///
6587         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
6588         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
6589         ///
6590         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
6591         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
6592         ///
6593         /// # Note
6594         ///
6595         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
6596         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
6597         ///
6598         /// Errors if `min_value_msat` is greater than total bitcoin supply.
6599         ///
6600         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
6601         /// on versions of LDK prior to 0.0.114.
6602         ///
6603         /// [`create_inbound_payment`]: Self::create_inbound_payment
6604         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
6605         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
6606                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
6607                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
6608                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
6609                         min_final_cltv_expiry)
6610         }
6611
6612         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
6613         /// previously returned from [`create_inbound_payment`].
6614         ///
6615         /// [`create_inbound_payment`]: Self::create_inbound_payment
6616         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
6617                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
6618         }
6619
6620         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
6621         /// are used when constructing the phantom invoice's route hints.
6622         ///
6623         /// [phantom node payments]: crate::sign::PhantomKeysManager
6624         pub fn get_phantom_scid(&self) -> u64 {
6625                 let best_block_height = self.best_block.read().unwrap().height();
6626                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
6627                 loop {
6628                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
6629                         // Ensure the generated scid doesn't conflict with a real channel.
6630                         match short_to_chan_info.get(&scid_candidate) {
6631                                 Some(_) => continue,
6632                                 None => return scid_candidate
6633                         }
6634                 }
6635         }
6636
6637         /// Gets route hints for use in receiving [phantom node payments].
6638         ///
6639         /// [phantom node payments]: crate::sign::PhantomKeysManager
6640         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
6641                 PhantomRouteHints {
6642                         channels: self.list_usable_channels(),
6643                         phantom_scid: self.get_phantom_scid(),
6644                         real_node_pubkey: self.get_our_node_id(),
6645                 }
6646         }
6647
6648         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
6649         /// used when constructing the route hints for HTLCs intended to be intercepted. See
6650         /// [`ChannelManager::forward_intercepted_htlc`].
6651         ///
6652         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
6653         /// times to get a unique scid.
6654         pub fn get_intercept_scid(&self) -> u64 {
6655                 let best_block_height = self.best_block.read().unwrap().height();
6656                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
6657                 loop {
6658                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
6659                         // Ensure the generated scid doesn't conflict with a real channel.
6660                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
6661                         return scid_candidate
6662                 }
6663         }
6664
6665         /// Gets inflight HTLC information by processing pending outbound payments that are in
6666         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
6667         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
6668                 let mut inflight_htlcs = InFlightHtlcs::new();
6669
6670                 let per_peer_state = self.per_peer_state.read().unwrap();
6671                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6672                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6673                         let peer_state = &mut *peer_state_lock;
6674                         for chan in peer_state.channel_by_id.values() {
6675                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
6676                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
6677                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
6678                                         }
6679                                 }
6680                         }
6681                 }
6682
6683                 inflight_htlcs
6684         }
6685
6686         #[cfg(any(test, feature = "_test_utils"))]
6687         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
6688                 let events = core::cell::RefCell::new(Vec::new());
6689                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
6690                 self.process_pending_events(&event_handler);
6691                 events.into_inner()
6692         }
6693
6694         #[cfg(feature = "_test_utils")]
6695         pub fn push_pending_event(&self, event: events::Event) {
6696                 let mut events = self.pending_events.lock().unwrap();
6697                 events.push_back((event, None));
6698         }
6699
6700         #[cfg(test)]
6701         pub fn pop_pending_event(&self) -> Option<events::Event> {
6702                 let mut events = self.pending_events.lock().unwrap();
6703                 events.pop_front().map(|(e, _)| e)
6704         }
6705
6706         #[cfg(test)]
6707         pub fn has_pending_payments(&self) -> bool {
6708                 self.pending_outbound_payments.has_pending_payments()
6709         }
6710
6711         #[cfg(test)]
6712         pub fn clear_pending_payments(&self) {
6713                 self.pending_outbound_payments.clear_pending_payments()
6714         }
6715
6716         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
6717         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
6718         /// operation. It will double-check that nothing *else* is also blocking the same channel from
6719         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
6720         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey, channel_funding_outpoint: OutPoint, mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
6721                 let mut errors = Vec::new();
6722                 loop {
6723                         let per_peer_state = self.per_peer_state.read().unwrap();
6724                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
6725                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
6726                                 let peer_state = &mut *peer_state_lck;
6727
6728                                 if let Some(blocker) = completed_blocker.take() {
6729                                         // Only do this on the first iteration of the loop.
6730                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
6731                                                 .get_mut(&channel_funding_outpoint.to_channel_id())
6732                                         {
6733                                                 blockers.retain(|iter| iter != &blocker);
6734                                         }
6735                                 }
6736
6737                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
6738                                         channel_funding_outpoint, counterparty_node_id) {
6739                                         // Check that, while holding the peer lock, we don't have anything else
6740                                         // blocking monitor updates for this channel. If we do, release the monitor
6741                                         // update(s) when those blockers complete.
6742                                         log_trace!(self.logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
6743                                                 log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6744                                         break;
6745                                 }
6746
6747                                 if let hash_map::Entry::Occupied(mut chan) = peer_state.channel_by_id.entry(channel_funding_outpoint.to_channel_id()) {
6748                                         debug_assert_eq!(chan.get().context.get_funding_txo().unwrap(), channel_funding_outpoint);
6749                                         if let Some((monitor_update, further_update_exists)) = chan.get_mut().unblock_next_blocked_monitor_update() {
6750                                                 log_debug!(self.logger, "Unlocking monitor updating for channel {} and updating monitor",
6751                                                         log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6752                                                 if let Err(e) = handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
6753                                                         peer_state_lck, peer_state, per_peer_state, chan)
6754                                                 {
6755                                                         errors.push((e, counterparty_node_id));
6756                                                 }
6757                                                 if further_update_exists {
6758                                                         // If there are more `ChannelMonitorUpdate`s to process, restart at the
6759                                                         // top of the loop.
6760                                                         continue;
6761                                                 }
6762                                         } else {
6763                                                 log_trace!(self.logger, "Unlocked monitor updating for channel {} without monitors to update",
6764                                                         log_bytes!(&channel_funding_outpoint.to_channel_id()[..]));
6765                                         }
6766                                 }
6767                         } else {
6768                                 log_debug!(self.logger,
6769                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
6770                                         log_pubkey!(counterparty_node_id));
6771                         }
6772                         break;
6773                 }
6774                 for (err, counterparty_node_id) in errors {
6775                         let res = Err::<(), _>(err);
6776                         let _ = handle_error!(self, res, counterparty_node_id);
6777                 }
6778         }
6779
6780         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
6781                 for action in actions {
6782                         match action {
6783                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6784                                         channel_funding_outpoint, counterparty_node_id
6785                                 } => {
6786                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, None);
6787                                 }
6788                         }
6789                 }
6790         }
6791
6792         /// Processes any events asynchronously in the order they were generated since the last call
6793         /// using the given event handler.
6794         ///
6795         /// See the trait-level documentation of [`EventsProvider`] for requirements.
6796         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
6797                 &self, handler: H
6798         ) {
6799                 let mut ev;
6800                 process_events_body!(self, ev, { handler(ev).await });
6801         }
6802 }
6803
6804 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>
6805 where
6806         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6807         T::Target: BroadcasterInterface,
6808         ES::Target: EntropySource,
6809         NS::Target: NodeSigner,
6810         SP::Target: SignerProvider,
6811         F::Target: FeeEstimator,
6812         R::Target: Router,
6813         L::Target: Logger,
6814 {
6815         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
6816         /// The returned array will contain `MessageSendEvent`s for different peers if
6817         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
6818         /// is always placed next to each other.
6819         ///
6820         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
6821         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
6822         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
6823         /// will randomly be placed first or last in the returned array.
6824         ///
6825         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
6826         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
6827         /// the `MessageSendEvent`s to the specific peer they were generated under.
6828         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
6829                 let events = RefCell::new(Vec::new());
6830                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
6831                         let mut result = self.process_background_events();
6832
6833                         // TODO: This behavior should be documented. It's unintuitive that we query
6834                         // ChannelMonitors when clearing other events.
6835                         if self.process_pending_monitor_events() {
6836                                 result = NotifyOption::DoPersist;
6837                         }
6838
6839                         if self.check_free_holding_cells() {
6840                                 result = NotifyOption::DoPersist;
6841                         }
6842                         if self.maybe_generate_initial_closing_signed() {
6843                                 result = NotifyOption::DoPersist;
6844                         }
6845
6846                         let mut pending_events = Vec::new();
6847                         let per_peer_state = self.per_peer_state.read().unwrap();
6848                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
6849                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6850                                 let peer_state = &mut *peer_state_lock;
6851                                 if peer_state.pending_msg_events.len() > 0 {
6852                                         pending_events.append(&mut peer_state.pending_msg_events);
6853                                 }
6854                         }
6855
6856                         if !pending_events.is_empty() {
6857                                 events.replace(pending_events);
6858                         }
6859
6860                         result
6861                 });
6862                 events.into_inner()
6863         }
6864 }
6865
6866 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>
6867 where
6868         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6869         T::Target: BroadcasterInterface,
6870         ES::Target: EntropySource,
6871         NS::Target: NodeSigner,
6872         SP::Target: SignerProvider,
6873         F::Target: FeeEstimator,
6874         R::Target: Router,
6875         L::Target: Logger,
6876 {
6877         /// Processes events that must be periodically handled.
6878         ///
6879         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
6880         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
6881         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
6882                 let mut ev;
6883                 process_events_body!(self, ev, handler.handle_event(ev));
6884         }
6885 }
6886
6887 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>
6888 where
6889         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6890         T::Target: BroadcasterInterface,
6891         ES::Target: EntropySource,
6892         NS::Target: NodeSigner,
6893         SP::Target: SignerProvider,
6894         F::Target: FeeEstimator,
6895         R::Target: Router,
6896         L::Target: Logger,
6897 {
6898         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
6899                 {
6900                         let best_block = self.best_block.read().unwrap();
6901                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
6902                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
6903                         assert_eq!(best_block.height(), height - 1,
6904                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
6905                 }
6906
6907                 self.transactions_confirmed(header, txdata, height);
6908                 self.best_block_updated(header, height);
6909         }
6910
6911         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
6912                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6913                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6914                 let new_height = height - 1;
6915                 {
6916                         let mut best_block = self.best_block.write().unwrap();
6917                         assert_eq!(best_block.block_hash(), header.block_hash(),
6918                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
6919                         assert_eq!(best_block.height(), height,
6920                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
6921                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
6922                 }
6923
6924                 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));
6925         }
6926 }
6927
6928 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>
6929 where
6930         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
6931         T::Target: BroadcasterInterface,
6932         ES::Target: EntropySource,
6933         NS::Target: NodeSigner,
6934         SP::Target: SignerProvider,
6935         F::Target: FeeEstimator,
6936         R::Target: Router,
6937         L::Target: Logger,
6938 {
6939         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
6940                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
6941                 // during initialization prior to the chain_monitor being fully configured in some cases.
6942                 // See the docs for `ChannelManagerReadArgs` for more.
6943
6944                 let block_hash = header.block_hash();
6945                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
6946
6947                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6948                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6949                 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)
6950                         .map(|(a, b)| (a, Vec::new(), b)));
6951
6952                 let last_best_block_height = self.best_block.read().unwrap().height();
6953                 if height < last_best_block_height {
6954                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
6955                         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));
6956                 }
6957         }
6958
6959         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
6960                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
6961                 // during initialization prior to the chain_monitor being fully configured in some cases.
6962                 // See the docs for `ChannelManagerReadArgs` for more.
6963
6964                 let block_hash = header.block_hash();
6965                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
6966
6967                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
6968                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
6969                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
6970
6971                 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));
6972
6973                 macro_rules! max_time {
6974                         ($timestamp: expr) => {
6975                                 loop {
6976                                         // Update $timestamp to be the max of its current value and the block
6977                                         // timestamp. This should keep us close to the current time without relying on
6978                                         // having an explicit local time source.
6979                                         // Just in case we end up in a race, we loop until we either successfully
6980                                         // update $timestamp or decide we don't need to.
6981                                         let old_serial = $timestamp.load(Ordering::Acquire);
6982                                         if old_serial >= header.time as usize { break; }
6983                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
6984                                                 break;
6985                                         }
6986                                 }
6987                         }
6988                 }
6989                 max_time!(self.highest_seen_timestamp);
6990                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
6991                 payment_secrets.retain(|_, inbound_payment| {
6992                         inbound_payment.expiry_time > header.time as u64
6993                 });
6994         }
6995
6996         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
6997                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
6998                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
6999                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7000                         let peer_state = &mut *peer_state_lock;
7001                         for chan in peer_state.channel_by_id.values() {
7002                                 if let (Some(funding_txo), Some(block_hash)) = (chan.context.get_funding_txo(), chan.context.get_funding_tx_confirmed_in()) {
7003                                         res.push((funding_txo.txid, Some(block_hash)));
7004                                 }
7005                         }
7006                 }
7007                 res
7008         }
7009
7010         fn transaction_unconfirmed(&self, txid: &Txid) {
7011                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock,
7012                         &self.persistence_notifier, || -> NotifyOption { NotifyOption::DoPersist });
7013                 self.do_chain_event(None, |channel| {
7014                         if let Some(funding_txo) = channel.context.get_funding_txo() {
7015                                 if funding_txo.txid == *txid {
7016                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
7017                                 } else { Ok((None, Vec::new(), None)) }
7018                         } else { Ok((None, Vec::new(), None)) }
7019                 });
7020         }
7021 }
7022
7023 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>
7024 where
7025         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7026         T::Target: BroadcasterInterface,
7027         ES::Target: EntropySource,
7028         NS::Target: NodeSigner,
7029         SP::Target: SignerProvider,
7030         F::Target: FeeEstimator,
7031         R::Target: Router,
7032         L::Target: Logger,
7033 {
7034         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
7035         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
7036         /// the function.
7037         fn do_chain_event<FN: Fn(&mut Channel<<SP::Target as SignerProvider>::Signer>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
7038                         (&self, height_opt: Option<u32>, f: FN) {
7039                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
7040                 // during initialization prior to the chain_monitor being fully configured in some cases.
7041                 // See the docs for `ChannelManagerReadArgs` for more.
7042
7043                 let mut failed_channels = Vec::new();
7044                 let mut timed_out_htlcs = Vec::new();
7045                 {
7046                         let per_peer_state = self.per_peer_state.read().unwrap();
7047                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7048                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7049                                 let peer_state = &mut *peer_state_lock;
7050                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7051                                 peer_state.channel_by_id.retain(|_, channel| {
7052                                         let res = f(channel);
7053                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
7054                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
7055                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
7056                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
7057                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
7058                                                 }
7059                                                 if let Some(channel_ready) = channel_ready_opt {
7060                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
7061                                                         if channel.context.is_usable() {
7062                                                                 log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", log_bytes!(channel.context.channel_id()));
7063                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
7064                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
7065                                                                                 node_id: channel.context.get_counterparty_node_id(),
7066                                                                                 msg,
7067                                                                         });
7068                                                                 }
7069                                                         } else {
7070                                                                 log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", log_bytes!(channel.context.channel_id()));
7071                                                         }
7072                                                 }
7073
7074                                                 {
7075                                                         let mut pending_events = self.pending_events.lock().unwrap();
7076                                                         emit_channel_ready_event!(pending_events, channel);
7077                                                 }
7078
7079                                                 if let Some(announcement_sigs) = announcement_sigs {
7080                                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(channel.context.channel_id()));
7081                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
7082                                                                 node_id: channel.context.get_counterparty_node_id(),
7083                                                                 msg: announcement_sigs,
7084                                                         });
7085                                                         if let Some(height) = height_opt {
7086                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.genesis_hash, height, &self.default_configuration) {
7087                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7088                                                                                 msg: announcement,
7089                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7090                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7091                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
7092                                                                         });
7093                                                                 }
7094                                                         }
7095                                                 }
7096                                                 if channel.is_our_channel_ready() {
7097                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
7098                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
7099                                                                 // to the short_to_chan_info map here. Note that we check whether we
7100                                                                 // can relay using the real SCID at relay-time (i.e.
7101                                                                 // enforce option_scid_alias then), and if the funding tx is ever
7102                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
7103                                                                 // is always consistent.
7104                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
7105                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
7106                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
7107                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
7108                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
7109                                                         }
7110                                                 }
7111                                         } else if let Err(reason) = res {
7112                                                 update_maps_on_chan_removal!(self, &channel.context);
7113                                                 // It looks like our counterparty went on-chain or funding transaction was
7114                                                 // reorged out of the main chain. Close the channel.
7115                                                 failed_channels.push(channel.context.force_shutdown(true));
7116                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
7117                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7118                                                                 msg: update
7119                                                         });
7120                                                 }
7121                                                 let reason_message = format!("{}", reason);
7122                                                 self.issue_channel_close_events(&channel.context, reason);
7123                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7124                                                         node_id: channel.context.get_counterparty_node_id(),
7125                                                         action: msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage {
7126                                                                 channel_id: channel.context.channel_id(),
7127                                                                 data: reason_message,
7128                                                         } },
7129                                                 });
7130                                                 return false;
7131                                         }
7132                                         true
7133                                 });
7134                         }
7135                 }
7136
7137                 if let Some(height) = height_opt {
7138                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
7139                                 payment.htlcs.retain(|htlc| {
7140                                         // If height is approaching the number of blocks we think it takes us to get
7141                                         // our commitment transaction confirmed before the HTLC expires, plus the
7142                                         // number of blocks we generally consider it to take to do a commitment update,
7143                                         // just give up on it and fail the HTLC.
7144                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
7145                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
7146                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
7147
7148                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
7149                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
7150                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
7151                                                 false
7152                                         } else { true }
7153                                 });
7154                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
7155                         });
7156
7157                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
7158                         intercepted_htlcs.retain(|_, htlc| {
7159                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
7160                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
7161                                                 short_channel_id: htlc.prev_short_channel_id,
7162                                                 user_channel_id: Some(htlc.prev_user_channel_id),
7163                                                 htlc_id: htlc.prev_htlc_id,
7164                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
7165                                                 phantom_shared_secret: None,
7166                                                 outpoint: htlc.prev_funding_outpoint,
7167                                         });
7168
7169                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
7170                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
7171                                                 _ => unreachable!(),
7172                                         };
7173                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
7174                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
7175                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
7176                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
7177                                         false
7178                                 } else { true }
7179                         });
7180                 }
7181
7182                 self.handle_init_event_channel_failures(failed_channels);
7183
7184                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
7185                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
7186                 }
7187         }
7188
7189         /// Gets a [`Future`] that completes when this [`ChannelManager`] needs to be persisted.
7190         ///
7191         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
7192         /// [`ChannelManager`] and should instead register actions to be taken later.
7193         ///
7194         pub fn get_persistable_update_future(&self) -> Future {
7195                 self.persistence_notifier.get_future()
7196         }
7197
7198         #[cfg(any(test, feature = "_test_utils"))]
7199         pub fn get_persistence_condvar_value(&self) -> bool {
7200                 self.persistence_notifier.notify_pending()
7201         }
7202
7203         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
7204         /// [`chain::Confirm`] interfaces.
7205         pub fn current_best_block(&self) -> BestBlock {
7206                 self.best_block.read().unwrap().clone()
7207         }
7208
7209         /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
7210         /// [`ChannelManager`].
7211         pub fn node_features(&self) -> NodeFeatures {
7212                 provided_node_features(&self.default_configuration)
7213         }
7214
7215         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
7216         /// [`ChannelManager`].
7217         ///
7218         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
7219         /// or not. Thus, this method is not public.
7220         #[cfg(any(feature = "_test_utils", test))]
7221         pub fn invoice_features(&self) -> Bolt11InvoiceFeatures {
7222                 provided_invoice_features(&self.default_configuration)
7223         }
7224
7225         /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
7226         /// [`ChannelManager`].
7227         pub fn channel_features(&self) -> ChannelFeatures {
7228                 provided_channel_features(&self.default_configuration)
7229         }
7230
7231         /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
7232         /// [`ChannelManager`].
7233         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
7234                 provided_channel_type_features(&self.default_configuration)
7235         }
7236
7237         /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
7238         /// [`ChannelManager`].
7239         pub fn init_features(&self) -> InitFeatures {
7240                 provided_init_features(&self.default_configuration)
7241         }
7242 }
7243
7244 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7245         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
7246 where
7247         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7248         T::Target: BroadcasterInterface,
7249         ES::Target: EntropySource,
7250         NS::Target: NodeSigner,
7251         SP::Target: SignerProvider,
7252         F::Target: FeeEstimator,
7253         R::Target: Router,
7254         L::Target: Logger,
7255 {
7256         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
7257                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7258                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, msg), *counterparty_node_id);
7259         }
7260
7261         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
7262                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7263                         "Dual-funded channels not supported".to_owned(),
7264                          msg.temporary_channel_id.clone())), *counterparty_node_id);
7265         }
7266
7267         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
7268                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7269                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
7270         }
7271
7272         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
7273                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7274                         "Dual-funded channels not supported".to_owned(),
7275                          msg.temporary_channel_id.clone())), *counterparty_node_id);
7276         }
7277
7278         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
7279                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7280                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
7281         }
7282
7283         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
7284                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7285                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
7286         }
7287
7288         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
7289                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7290                 let _ = handle_error!(self, self.internal_channel_ready(counterparty_node_id, msg), *counterparty_node_id);
7291         }
7292
7293         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
7294                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7295                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
7296         }
7297
7298         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
7299                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7300                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
7301         }
7302
7303         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
7304                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7305                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
7306         }
7307
7308         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
7309                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7310                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
7311         }
7312
7313         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
7314                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7315                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
7316         }
7317
7318         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
7319                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7320                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
7321         }
7322
7323         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
7324                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7325                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
7326         }
7327
7328         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
7329                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7330                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
7331         }
7332
7333         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
7334                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7335                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
7336         }
7337
7338         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
7339                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7340                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
7341         }
7342
7343         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
7344                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
7345                         let force_persist = self.process_background_events();
7346                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
7347                                 if force_persist == NotifyOption::DoPersist { NotifyOption::DoPersist } else { persist }
7348                         } else {
7349                                 NotifyOption::SkipPersist
7350                         }
7351                 });
7352         }
7353
7354         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
7355                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7356                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
7357         }
7358
7359         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
7360                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7361                 let mut failed_channels = Vec::new();
7362                 let mut per_peer_state = self.per_peer_state.write().unwrap();
7363                 let remove_peer = {
7364                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates.",
7365                                 log_pubkey!(counterparty_node_id));
7366                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
7367                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7368                                 let peer_state = &mut *peer_state_lock;
7369                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7370                                 peer_state.channel_by_id.retain(|_, chan| {
7371                                         chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
7372                                         if chan.is_shutdown() {
7373                                                 update_maps_on_chan_removal!(self, &chan.context);
7374                                                 self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7375                                                 return false;
7376                                         }
7377                                         true
7378                                 });
7379                                 peer_state.inbound_v1_channel_by_id.retain(|_, chan| {
7380                                         update_maps_on_chan_removal!(self, &chan.context);
7381                                         self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7382                                         false
7383                                 });
7384                                 peer_state.outbound_v1_channel_by_id.retain(|_, chan| {
7385                                         update_maps_on_chan_removal!(self, &chan.context);
7386                                         self.issue_channel_close_events(&chan.context, ClosureReason::DisconnectedPeer);
7387                                         false
7388                                 });
7389                                 // Note that we don't bother generating any events for pre-accept channels -
7390                                 // they're not considered "channels" yet from the PoV of our events interface.
7391                                 peer_state.inbound_channel_request_by_id.clear();
7392                                 pending_msg_events.retain(|msg| {
7393                                         match msg {
7394                                                 // V1 Channel Establishment
7395                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
7396                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
7397                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
7398                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
7399                                                 // V2 Channel Establishment
7400                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
7401                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
7402                                                 // Common Channel Establishment
7403                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
7404                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
7405                                                 // Interactive Transaction Construction
7406                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
7407                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
7408                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
7409                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
7410                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
7411                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
7412                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
7413                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
7414                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
7415                                                 // Channel Operations
7416                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
7417                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
7418                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
7419                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
7420                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
7421                                                 &events::MessageSendEvent::HandleError { .. } => false,
7422                                                 // Gossip
7423                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
7424                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
7425                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
7426                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
7427                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
7428                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
7429                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
7430                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
7431                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
7432                                         }
7433                                 });
7434                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
7435                                 peer_state.is_connected = false;
7436                                 peer_state.ok_to_remove(true)
7437                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
7438                 };
7439                 if remove_peer {
7440                         per_peer_state.remove(counterparty_node_id);
7441                 }
7442                 mem::drop(per_peer_state);
7443
7444                 for failure in failed_channels.drain(..) {
7445                         self.finish_force_close_channel(failure);
7446                 }
7447         }
7448
7449         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
7450                 if !init_msg.features.supports_static_remote_key() {
7451                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
7452                         return Err(());
7453                 }
7454
7455                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7456
7457                 // If we have too many peers connected which don't have funded channels, disconnect the
7458                 // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
7459                 // unfunded channels taking up space in memory for disconnected peers, we still let new
7460                 // peers connect, but we'll reject new channels from them.
7461                 let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
7462                 let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
7463
7464                 {
7465                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
7466                         match peer_state_lock.entry(counterparty_node_id.clone()) {
7467                                 hash_map::Entry::Vacant(e) => {
7468                                         if inbound_peer_limited {
7469                                                 return Err(());
7470                                         }
7471                                         e.insert(Mutex::new(PeerState {
7472                                                 channel_by_id: HashMap::new(),
7473                                                 outbound_v1_channel_by_id: HashMap::new(),
7474                                                 inbound_v1_channel_by_id: HashMap::new(),
7475                                                 inbound_channel_request_by_id: HashMap::new(),
7476                                                 latest_features: init_msg.features.clone(),
7477                                                 pending_msg_events: Vec::new(),
7478                                                 in_flight_monitor_updates: BTreeMap::new(),
7479                                                 monitor_update_blocked_actions: BTreeMap::new(),
7480                                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
7481                                                 is_connected: true,
7482                                         }));
7483                                 },
7484                                 hash_map::Entry::Occupied(e) => {
7485                                         let mut peer_state = e.get().lock().unwrap();
7486                                         peer_state.latest_features = init_msg.features.clone();
7487
7488                                         let best_block_height = self.best_block.read().unwrap().height();
7489                                         if inbound_peer_limited &&
7490                                                 Self::unfunded_channel_count(&*peer_state, best_block_height) ==
7491                                                 peer_state.channel_by_id.len()
7492                                         {
7493                                                 return Err(());
7494                                         }
7495
7496                                         debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
7497                                         peer_state.is_connected = true;
7498                                 },
7499                         }
7500                 }
7501
7502                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
7503
7504                 let per_peer_state = self.per_peer_state.read().unwrap();
7505                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
7506                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7507                         let peer_state = &mut *peer_state_lock;
7508                         let pending_msg_events = &mut peer_state.pending_msg_events;
7509
7510                         // Since unfunded channel maps are cleared upon disconnecting a peer, and they're not persisted
7511                         // (so won't be recovered after a crash) we don't need to bother closing unfunded channels and
7512                         // clearing their maps here. Instead we can just send queue channel_reestablish messages for
7513                         // channels in the channel_by_id map.
7514                         peer_state.channel_by_id.iter_mut().for_each(|(_, chan)| {
7515                                 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
7516                                         node_id: chan.context.get_counterparty_node_id(),
7517                                         msg: chan.get_channel_reestablish(&self.logger),
7518                                 });
7519                         });
7520                 }
7521                 //TODO: Also re-broadcast announcement_signatures
7522                 Ok(())
7523         }
7524
7525         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
7526                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7527
7528                 if msg.channel_id == [0; 32] {
7529                         let channel_ids: Vec<[u8; 32]> = {
7530                                 let per_peer_state = self.per_peer_state.read().unwrap();
7531                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
7532                                 if peer_state_mutex_opt.is_none() { return; }
7533                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7534                                 let peer_state = &mut *peer_state_lock;
7535                                 // Note that we don't bother generating any events for pre-accept channels -
7536                                 // they're not considered "channels" yet from the PoV of our events interface.
7537                                 peer_state.inbound_channel_request_by_id.clear();
7538                                 peer_state.channel_by_id.keys().cloned()
7539                                         .chain(peer_state.outbound_v1_channel_by_id.keys().cloned())
7540                                         .chain(peer_state.inbound_v1_channel_by_id.keys().cloned()).collect()
7541                         };
7542                         for channel_id in channel_ids {
7543                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
7544                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
7545                         }
7546                 } else {
7547                         {
7548                                 // First check if we can advance the channel type and try again.
7549                                 let per_peer_state = self.per_peer_state.read().unwrap();
7550                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
7551                                 if peer_state_mutex_opt.is_none() { return; }
7552                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7553                                 let peer_state = &mut *peer_state_lock;
7554                                 if let Some(chan) = peer_state.outbound_v1_channel_by_id.get_mut(&msg.channel_id) {
7555                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.genesis_hash, &self.fee_estimator) {
7556                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
7557                                                         node_id: *counterparty_node_id,
7558                                                         msg,
7559                                                 });
7560                                                 return;
7561                                         }
7562                                 }
7563                         }
7564
7565                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
7566                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
7567                 }
7568         }
7569
7570         fn provided_node_features(&self) -> NodeFeatures {
7571                 provided_node_features(&self.default_configuration)
7572         }
7573
7574         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
7575                 provided_init_features(&self.default_configuration)
7576         }
7577
7578         fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
7579                 Some(vec![ChainHash::from(&self.genesis_hash[..])])
7580         }
7581
7582         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
7583                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7584                         "Dual-funded channels not supported".to_owned(),
7585                          msg.channel_id.clone())), *counterparty_node_id);
7586         }
7587
7588         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
7589                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7590                         "Dual-funded channels not supported".to_owned(),
7591                          msg.channel_id.clone())), *counterparty_node_id);
7592         }
7593
7594         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
7595                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7596                         "Dual-funded channels not supported".to_owned(),
7597                          msg.channel_id.clone())), *counterparty_node_id);
7598         }
7599
7600         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
7601                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7602                         "Dual-funded channels not supported".to_owned(),
7603                          msg.channel_id.clone())), *counterparty_node_id);
7604         }
7605
7606         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
7607                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7608                         "Dual-funded channels not supported".to_owned(),
7609                          msg.channel_id.clone())), *counterparty_node_id);
7610         }
7611
7612         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
7613                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7614                         "Dual-funded channels not supported".to_owned(),
7615                          msg.channel_id.clone())), *counterparty_node_id);
7616         }
7617
7618         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
7619                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7620                         "Dual-funded channels not supported".to_owned(),
7621                          msg.channel_id.clone())), *counterparty_node_id);
7622         }
7623
7624         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
7625                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7626                         "Dual-funded channels not supported".to_owned(),
7627                          msg.channel_id.clone())), *counterparty_node_id);
7628         }
7629
7630         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
7631                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
7632                         "Dual-funded channels not supported".to_owned(),
7633                          msg.channel_id.clone())), *counterparty_node_id);
7634         }
7635 }
7636
7637 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
7638 /// [`ChannelManager`].
7639 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
7640         let mut node_features = provided_init_features(config).to_context();
7641         node_features.set_keysend_optional();
7642         node_features
7643 }
7644
7645 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags which are provided by or required by
7646 /// [`ChannelManager`].
7647 ///
7648 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
7649 /// or not. Thus, this method is not public.
7650 #[cfg(any(feature = "_test_utils", test))]
7651 pub(crate) fn provided_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
7652         provided_init_features(config).to_context()
7653 }
7654
7655 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
7656 /// [`ChannelManager`].
7657 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
7658         provided_init_features(config).to_context()
7659 }
7660
7661 /// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by
7662 /// [`ChannelManager`].
7663 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
7664         ChannelTypeFeatures::from_init(&provided_init_features(config))
7665 }
7666
7667 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
7668 /// [`ChannelManager`].
7669 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
7670         // Note that if new features are added here which other peers may (eventually) require, we
7671         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
7672         // [`ErroringMessageHandler`].
7673         let mut features = InitFeatures::empty();
7674         features.set_data_loss_protect_required();
7675         features.set_upfront_shutdown_script_optional();
7676         features.set_variable_length_onion_required();
7677         features.set_static_remote_key_required();
7678         features.set_payment_secret_required();
7679         features.set_basic_mpp_optional();
7680         features.set_wumbo_optional();
7681         features.set_shutdown_any_segwit_optional();
7682         features.set_channel_type_optional();
7683         features.set_scid_privacy_optional();
7684         features.set_zero_conf_optional();
7685         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
7686                 features.set_anchors_zero_fee_htlc_tx_optional();
7687         }
7688         features
7689 }
7690
7691 const SERIALIZATION_VERSION: u8 = 1;
7692 const MIN_SERIALIZATION_VERSION: u8 = 1;
7693
7694 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
7695         (2, fee_base_msat, required),
7696         (4, fee_proportional_millionths, required),
7697         (6, cltv_expiry_delta, required),
7698 });
7699
7700 impl_writeable_tlv_based!(ChannelCounterparty, {
7701         (2, node_id, required),
7702         (4, features, required),
7703         (6, unspendable_punishment_reserve, required),
7704         (8, forwarding_info, option),
7705         (9, outbound_htlc_minimum_msat, option),
7706         (11, outbound_htlc_maximum_msat, option),
7707 });
7708
7709 impl Writeable for ChannelDetails {
7710         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7711                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
7712                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
7713                 let user_channel_id_low = self.user_channel_id as u64;
7714                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
7715                 write_tlv_fields!(writer, {
7716                         (1, self.inbound_scid_alias, option),
7717                         (2, self.channel_id, required),
7718                         (3, self.channel_type, option),
7719                         (4, self.counterparty, required),
7720                         (5, self.outbound_scid_alias, option),
7721                         (6, self.funding_txo, option),
7722                         (7, self.config, option),
7723                         (8, self.short_channel_id, option),
7724                         (9, self.confirmations, option),
7725                         (10, self.channel_value_satoshis, required),
7726                         (12, self.unspendable_punishment_reserve, option),
7727                         (14, user_channel_id_low, required),
7728                         (16, self.next_outbound_htlc_limit_msat, required),  // Forwards compatibility for removed balance_msat field.
7729                         (18, self.outbound_capacity_msat, required),
7730                         (19, self.next_outbound_htlc_limit_msat, required),
7731                         (20, self.inbound_capacity_msat, required),
7732                         (21, self.next_outbound_htlc_minimum_msat, required),
7733                         (22, self.confirmations_required, option),
7734                         (24, self.force_close_spend_delay, option),
7735                         (26, self.is_outbound, required),
7736                         (28, self.is_channel_ready, required),
7737                         (30, self.is_usable, required),
7738                         (32, self.is_public, required),
7739                         (33, self.inbound_htlc_minimum_msat, option),
7740                         (35, self.inbound_htlc_maximum_msat, option),
7741                         (37, user_channel_id_high_opt, option),
7742                         (39, self.feerate_sat_per_1000_weight, option),
7743                         (41, self.channel_shutdown_state, option),
7744                 });
7745                 Ok(())
7746         }
7747 }
7748
7749 impl Readable for ChannelDetails {
7750         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7751                 _init_and_read_tlv_fields!(reader, {
7752                         (1, inbound_scid_alias, option),
7753                         (2, channel_id, required),
7754                         (3, channel_type, option),
7755                         (4, counterparty, required),
7756                         (5, outbound_scid_alias, option),
7757                         (6, funding_txo, option),
7758                         (7, config, option),
7759                         (8, short_channel_id, option),
7760                         (9, confirmations, option),
7761                         (10, channel_value_satoshis, required),
7762                         (12, unspendable_punishment_reserve, option),
7763                         (14, user_channel_id_low, required),
7764                         (16, _balance_msat, option),  // Backwards compatibility for removed balance_msat field.
7765                         (18, outbound_capacity_msat, required),
7766                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
7767                         // filled in, so we can safely unwrap it here.
7768                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
7769                         (20, inbound_capacity_msat, required),
7770                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
7771                         (22, confirmations_required, option),
7772                         (24, force_close_spend_delay, option),
7773                         (26, is_outbound, required),
7774                         (28, is_channel_ready, required),
7775                         (30, is_usable, required),
7776                         (32, is_public, required),
7777                         (33, inbound_htlc_minimum_msat, option),
7778                         (35, inbound_htlc_maximum_msat, option),
7779                         (37, user_channel_id_high_opt, option),
7780                         (39, feerate_sat_per_1000_weight, option),
7781                         (41, channel_shutdown_state, option),
7782                 });
7783
7784                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
7785                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
7786                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
7787                 let user_channel_id = user_channel_id_low as u128 +
7788                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
7789
7790                 let _balance_msat: Option<u64> = _balance_msat;
7791
7792                 Ok(Self {
7793                         inbound_scid_alias,
7794                         channel_id: channel_id.0.unwrap(),
7795                         channel_type,
7796                         counterparty: counterparty.0.unwrap(),
7797                         outbound_scid_alias,
7798                         funding_txo,
7799                         config,
7800                         short_channel_id,
7801                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
7802                         unspendable_punishment_reserve,
7803                         user_channel_id,
7804                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
7805                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
7806                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
7807                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
7808                         confirmations_required,
7809                         confirmations,
7810                         force_close_spend_delay,
7811                         is_outbound: is_outbound.0.unwrap(),
7812                         is_channel_ready: is_channel_ready.0.unwrap(),
7813                         is_usable: is_usable.0.unwrap(),
7814                         is_public: is_public.0.unwrap(),
7815                         inbound_htlc_minimum_msat,
7816                         inbound_htlc_maximum_msat,
7817                         feerate_sat_per_1000_weight,
7818                         channel_shutdown_state,
7819                 })
7820         }
7821 }
7822
7823 impl_writeable_tlv_based!(PhantomRouteHints, {
7824         (2, channels, required_vec),
7825         (4, phantom_scid, required),
7826         (6, real_node_pubkey, required),
7827 });
7828
7829 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
7830         (0, Forward) => {
7831                 (0, onion_packet, required),
7832                 (2, short_channel_id, required),
7833         },
7834         (1, Receive) => {
7835                 (0, payment_data, required),
7836                 (1, phantom_shared_secret, option),
7837                 (2, incoming_cltv_expiry, required),
7838                 (3, payment_metadata, option),
7839                 (5, custom_tlvs, optional_vec),
7840         },
7841         (2, ReceiveKeysend) => {
7842                 (0, payment_preimage, required),
7843                 (2, incoming_cltv_expiry, required),
7844                 (3, payment_metadata, option),
7845                 (4, payment_data, option), // Added in 0.0.116
7846                 (5, custom_tlvs, optional_vec),
7847         },
7848 ;);
7849
7850 impl_writeable_tlv_based!(PendingHTLCInfo, {
7851         (0, routing, required),
7852         (2, incoming_shared_secret, required),
7853         (4, payment_hash, required),
7854         (6, outgoing_amt_msat, required),
7855         (8, outgoing_cltv_value, required),
7856         (9, incoming_amt_msat, option),
7857         (10, skimmed_fee_msat, option),
7858 });
7859
7860
7861 impl Writeable for HTLCFailureMsg {
7862         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7863                 match self {
7864                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
7865                                 0u8.write(writer)?;
7866                                 channel_id.write(writer)?;
7867                                 htlc_id.write(writer)?;
7868                                 reason.write(writer)?;
7869                         },
7870                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7871                                 channel_id, htlc_id, sha256_of_onion, failure_code
7872                         }) => {
7873                                 1u8.write(writer)?;
7874                                 channel_id.write(writer)?;
7875                                 htlc_id.write(writer)?;
7876                                 sha256_of_onion.write(writer)?;
7877                                 failure_code.write(writer)?;
7878                         },
7879                 }
7880                 Ok(())
7881         }
7882 }
7883
7884 impl Readable for HTLCFailureMsg {
7885         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7886                 let id: u8 = Readable::read(reader)?;
7887                 match id {
7888                         0 => {
7889                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
7890                                         channel_id: Readable::read(reader)?,
7891                                         htlc_id: Readable::read(reader)?,
7892                                         reason: Readable::read(reader)?,
7893                                 }))
7894                         },
7895                         1 => {
7896                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
7897                                         channel_id: Readable::read(reader)?,
7898                                         htlc_id: Readable::read(reader)?,
7899                                         sha256_of_onion: Readable::read(reader)?,
7900                                         failure_code: Readable::read(reader)?,
7901                                 }))
7902                         },
7903                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
7904                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
7905                         // messages contained in the variants.
7906                         // In version 0.0.101, support for reading the variants with these types was added, and
7907                         // we should migrate to writing these variants when UpdateFailHTLC or
7908                         // UpdateFailMalformedHTLC get TLV fields.
7909                         2 => {
7910                                 let length: BigSize = Readable::read(reader)?;
7911                                 let mut s = FixedLengthReader::new(reader, length.0);
7912                                 let res = Readable::read(&mut s)?;
7913                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
7914                                 Ok(HTLCFailureMsg::Relay(res))
7915                         },
7916                         3 => {
7917                                 let length: BigSize = Readable::read(reader)?;
7918                                 let mut s = FixedLengthReader::new(reader, length.0);
7919                                 let res = Readable::read(&mut s)?;
7920                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
7921                                 Ok(HTLCFailureMsg::Malformed(res))
7922                         },
7923                         _ => Err(DecodeError::UnknownRequiredFeature),
7924                 }
7925         }
7926 }
7927
7928 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
7929         (0, Forward),
7930         (1, Fail),
7931 );
7932
7933 impl_writeable_tlv_based!(HTLCPreviousHopData, {
7934         (0, short_channel_id, required),
7935         (1, phantom_shared_secret, option),
7936         (2, outpoint, required),
7937         (4, htlc_id, required),
7938         (6, incoming_packet_shared_secret, required),
7939         (7, user_channel_id, option),
7940 });
7941
7942 impl Writeable for ClaimableHTLC {
7943         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
7944                 let (payment_data, keysend_preimage) = match &self.onion_payload {
7945                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
7946                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
7947                 };
7948                 write_tlv_fields!(writer, {
7949                         (0, self.prev_hop, required),
7950                         (1, self.total_msat, required),
7951                         (2, self.value, required),
7952                         (3, self.sender_intended_value, required),
7953                         (4, payment_data, option),
7954                         (5, self.total_value_received, option),
7955                         (6, self.cltv_expiry, required),
7956                         (8, keysend_preimage, option),
7957                         (10, self.counterparty_skimmed_fee_msat, option),
7958                 });
7959                 Ok(())
7960         }
7961 }
7962
7963 impl Readable for ClaimableHTLC {
7964         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
7965                 _init_and_read_tlv_fields!(reader, {
7966                         (0, prev_hop, required),
7967                         (1, total_msat, option),
7968                         (2, value_ser, required),
7969                         (3, sender_intended_value, option),
7970                         (4, payment_data_opt, option),
7971                         (5, total_value_received, option),
7972                         (6, cltv_expiry, required),
7973                         (8, keysend_preimage, option),
7974                         (10, counterparty_skimmed_fee_msat, option),
7975                 });
7976                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
7977                 let value = value_ser.0.unwrap();
7978                 let onion_payload = match keysend_preimage {
7979                         Some(p) => {
7980                                 if payment_data.is_some() {
7981                                         return Err(DecodeError::InvalidValue)
7982                                 }
7983                                 if total_msat.is_none() {
7984                                         total_msat = Some(value);
7985                                 }
7986                                 OnionPayload::Spontaneous(p)
7987                         },
7988                         None => {
7989                                 if total_msat.is_none() {
7990                                         if payment_data.is_none() {
7991                                                 return Err(DecodeError::InvalidValue)
7992                                         }
7993                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
7994                                 }
7995                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
7996                         },
7997                 };
7998                 Ok(Self {
7999                         prev_hop: prev_hop.0.unwrap(),
8000                         timer_ticks: 0,
8001                         value,
8002                         sender_intended_value: sender_intended_value.unwrap_or(value),
8003                         total_value_received,
8004                         total_msat: total_msat.unwrap(),
8005                         onion_payload,
8006                         cltv_expiry: cltv_expiry.0.unwrap(),
8007                         counterparty_skimmed_fee_msat,
8008                 })
8009         }
8010 }
8011
8012 impl Readable for HTLCSource {
8013         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8014                 let id: u8 = Readable::read(reader)?;
8015                 match id {
8016                         0 => {
8017                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
8018                                 let mut first_hop_htlc_msat: u64 = 0;
8019                                 let mut path_hops = Vec::new();
8020                                 let mut payment_id = None;
8021                                 let mut payment_params: Option<PaymentParameters> = None;
8022                                 let mut blinded_tail: Option<BlindedTail> = None;
8023                                 read_tlv_fields!(reader, {
8024                                         (0, session_priv, required),
8025                                         (1, payment_id, option),
8026                                         (2, first_hop_htlc_msat, required),
8027                                         (4, path_hops, required_vec),
8028                                         (5, payment_params, (option: ReadableArgs, 0)),
8029                                         (6, blinded_tail, option),
8030                                 });
8031                                 if payment_id.is_none() {
8032                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
8033                                         // instead.
8034                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
8035                                 }
8036                                 let path = Path { hops: path_hops, blinded_tail };
8037                                 if path.hops.len() == 0 {
8038                                         return Err(DecodeError::InvalidValue);
8039                                 }
8040                                 if let Some(params) = payment_params.as_mut() {
8041                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
8042                                                 if final_cltv_expiry_delta == &0 {
8043                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
8044                                                 }
8045                                         }
8046                                 }
8047                                 Ok(HTLCSource::OutboundRoute {
8048                                         session_priv: session_priv.0.unwrap(),
8049                                         first_hop_htlc_msat,
8050                                         path,
8051                                         payment_id: payment_id.unwrap(),
8052                                 })
8053                         }
8054                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
8055                         _ => Err(DecodeError::UnknownRequiredFeature),
8056                 }
8057         }
8058 }
8059
8060 impl Writeable for HTLCSource {
8061         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
8062                 match self {
8063                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
8064                                 0u8.write(writer)?;
8065                                 let payment_id_opt = Some(payment_id);
8066                                 write_tlv_fields!(writer, {
8067                                         (0, session_priv, required),
8068                                         (1, payment_id_opt, option),
8069                                         (2, first_hop_htlc_msat, required),
8070                                         // 3 was previously used to write a PaymentSecret for the payment.
8071                                         (4, path.hops, required_vec),
8072                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
8073                                         (6, path.blinded_tail, option),
8074                                  });
8075                         }
8076                         HTLCSource::PreviousHopData(ref field) => {
8077                                 1u8.write(writer)?;
8078                                 field.write(writer)?;
8079                         }
8080                 }
8081                 Ok(())
8082         }
8083 }
8084
8085 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
8086         (0, forward_info, required),
8087         (1, prev_user_channel_id, (default_value, 0)),
8088         (2, prev_short_channel_id, required),
8089         (4, prev_htlc_id, required),
8090         (6, prev_funding_outpoint, required),
8091 });
8092
8093 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
8094         (1, FailHTLC) => {
8095                 (0, htlc_id, required),
8096                 (2, err_packet, required),
8097         };
8098         (0, AddHTLC)
8099 );
8100
8101 impl_writeable_tlv_based!(PendingInboundPayment, {
8102         (0, payment_secret, required),
8103         (2, expiry_time, required),
8104         (4, user_payment_id, required),
8105         (6, payment_preimage, required),
8106         (8, min_value_msat, required),
8107 });
8108
8109 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>
8110 where
8111         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8112         T::Target: BroadcasterInterface,
8113         ES::Target: EntropySource,
8114         NS::Target: NodeSigner,
8115         SP::Target: SignerProvider,
8116         F::Target: FeeEstimator,
8117         R::Target: Router,
8118         L::Target: Logger,
8119 {
8120         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
8121                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
8122
8123                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
8124
8125                 self.genesis_hash.write(writer)?;
8126                 {
8127                         let best_block = self.best_block.read().unwrap();
8128                         best_block.height().write(writer)?;
8129                         best_block.block_hash().write(writer)?;
8130                 }
8131
8132                 let mut serializable_peer_count: u64 = 0;
8133                 {
8134                         let per_peer_state = self.per_peer_state.read().unwrap();
8135                         let mut unfunded_channels = 0;
8136                         let mut number_of_channels = 0;
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                                 if !peer_state.ok_to_remove(false) {
8141                                         serializable_peer_count += 1;
8142                                 }
8143                                 number_of_channels += peer_state.channel_by_id.len();
8144                                 for (_, channel) in peer_state.channel_by_id.iter() {
8145                                         if !channel.context.is_funding_initiated() {
8146                                                 unfunded_channels += 1;
8147                                         }
8148                                 }
8149                         }
8150
8151                         ((number_of_channels - unfunded_channels) as u64).write(writer)?;
8152
8153                         for (_, peer_state_mutex) in per_peer_state.iter() {
8154                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8155                                 let peer_state = &mut *peer_state_lock;
8156                                 for (_, channel) in peer_state.channel_by_id.iter() {
8157                                         if channel.context.is_funding_initiated() {
8158                                                 channel.write(writer)?;
8159                                         }
8160                                 }
8161                         }
8162                 }
8163
8164                 {
8165                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
8166                         (forward_htlcs.len() as u64).write(writer)?;
8167                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
8168                                 short_channel_id.write(writer)?;
8169                                 (pending_forwards.len() as u64).write(writer)?;
8170                                 for forward in pending_forwards {
8171                                         forward.write(writer)?;
8172                                 }
8173                         }
8174                 }
8175
8176                 let per_peer_state = self.per_peer_state.write().unwrap();
8177
8178                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
8179                 let claimable_payments = self.claimable_payments.lock().unwrap();
8180                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
8181
8182                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
8183                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
8184                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
8185                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
8186                         payment_hash.write(writer)?;
8187                         (payment.htlcs.len() as u64).write(writer)?;
8188                         for htlc in payment.htlcs.iter() {
8189                                 htlc.write(writer)?;
8190                         }
8191                         htlc_purposes.push(&payment.purpose);
8192                         htlc_onion_fields.push(&payment.onion_fields);
8193                 }
8194
8195                 let mut monitor_update_blocked_actions_per_peer = None;
8196                 let mut peer_states = Vec::new();
8197                 for (_, peer_state_mutex) in per_peer_state.iter() {
8198                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
8199                         // of a lockorder violation deadlock - no other thread can be holding any
8200                         // per_peer_state lock at all.
8201                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
8202                 }
8203
8204                 (serializable_peer_count).write(writer)?;
8205                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
8206                         // Peers which we have no channels to should be dropped once disconnected. As we
8207                         // disconnect all peers when shutting down and serializing the ChannelManager, we
8208                         // consider all peers as disconnected here. There's therefore no need write peers with
8209                         // no channels.
8210                         if !peer_state.ok_to_remove(false) {
8211                                 peer_pubkey.write(writer)?;
8212                                 peer_state.latest_features.write(writer)?;
8213                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
8214                                         monitor_update_blocked_actions_per_peer
8215                                                 .get_or_insert_with(Vec::new)
8216                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
8217                                 }
8218                         }
8219                 }
8220
8221                 let events = self.pending_events.lock().unwrap();
8222                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
8223                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
8224                 // refuse to read the new ChannelManager.
8225                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
8226                 if events_not_backwards_compatible {
8227                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
8228                         // well save the space and not write any events here.
8229                         0u64.write(writer)?;
8230                 } else {
8231                         (events.len() as u64).write(writer)?;
8232                         for (event, _) in events.iter() {
8233                                 event.write(writer)?;
8234                         }
8235                 }
8236
8237                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
8238                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
8239                 // the closing monitor updates were always effectively replayed on startup (either directly
8240                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
8241                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
8242                 0u64.write(writer)?;
8243
8244                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
8245                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
8246                 // likely to be identical.
8247                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
8248                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
8249
8250                 (pending_inbound_payments.len() as u64).write(writer)?;
8251                 for (hash, pending_payment) in pending_inbound_payments.iter() {
8252                         hash.write(writer)?;
8253                         pending_payment.write(writer)?;
8254                 }
8255
8256                 // For backwards compat, write the session privs and their total length.
8257                 let mut num_pending_outbounds_compat: u64 = 0;
8258                 for (_, outbound) in pending_outbound_payments.iter() {
8259                         if !outbound.is_fulfilled() && !outbound.abandoned() {
8260                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
8261                         }
8262                 }
8263                 num_pending_outbounds_compat.write(writer)?;
8264                 for (_, outbound) in pending_outbound_payments.iter() {
8265                         match outbound {
8266                                 PendingOutboundPayment::Legacy { session_privs } |
8267                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
8268                                         for session_priv in session_privs.iter() {
8269                                                 session_priv.write(writer)?;
8270                                         }
8271                                 }
8272                                 PendingOutboundPayment::Fulfilled { .. } => {},
8273                                 PendingOutboundPayment::Abandoned { .. } => {},
8274                         }
8275                 }
8276
8277                 // Encode without retry info for 0.0.101 compatibility.
8278                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
8279                 for (id, outbound) in pending_outbound_payments.iter() {
8280                         match outbound {
8281                                 PendingOutboundPayment::Legacy { session_privs } |
8282                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
8283                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
8284                                 },
8285                                 _ => {},
8286                         }
8287                 }
8288
8289                 let mut pending_intercepted_htlcs = None;
8290                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
8291                 if our_pending_intercepts.len() != 0 {
8292                         pending_intercepted_htlcs = Some(our_pending_intercepts);
8293                 }
8294
8295                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
8296                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
8297                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
8298                         // map. Thus, if there are no entries we skip writing a TLV for it.
8299                         pending_claiming_payments = None;
8300                 }
8301
8302                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
8303                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
8304                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
8305                                 if !updates.is_empty() {
8306                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
8307                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
8308                                 }
8309                         }
8310                 }
8311
8312                 write_tlv_fields!(writer, {
8313                         (1, pending_outbound_payments_no_retry, required),
8314                         (2, pending_intercepted_htlcs, option),
8315                         (3, pending_outbound_payments, required),
8316                         (4, pending_claiming_payments, option),
8317                         (5, self.our_network_pubkey, required),
8318                         (6, monitor_update_blocked_actions_per_peer, option),
8319                         (7, self.fake_scid_rand_bytes, required),
8320                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
8321                         (9, htlc_purposes, required_vec),
8322                         (10, in_flight_monitor_updates, option),
8323                         (11, self.probing_cookie_secret, required),
8324                         (13, htlc_onion_fields, optional_vec),
8325                 });
8326
8327                 Ok(())
8328         }
8329 }
8330
8331 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
8332         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
8333                 (self.len() as u64).write(w)?;
8334                 for (event, action) in self.iter() {
8335                         event.write(w)?;
8336                         action.write(w)?;
8337                         #[cfg(debug_assertions)] {
8338                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
8339                                 // be persisted and are regenerated on restart. However, if such an event has a
8340                                 // post-event-handling action we'll write nothing for the event and would have to
8341                                 // either forget the action or fail on deserialization (which we do below). Thus,
8342                                 // check that the event is sane here.
8343                                 let event_encoded = event.encode();
8344                                 let event_read: Option<Event> =
8345                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
8346                                 if action.is_some() { assert!(event_read.is_some()); }
8347                         }
8348                 }
8349                 Ok(())
8350         }
8351 }
8352 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
8353         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
8354                 let len: u64 = Readable::read(reader)?;
8355                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
8356                 let mut events: Self = VecDeque::with_capacity(cmp::min(
8357                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
8358                         len) as usize);
8359                 for _ in 0..len {
8360                         let ev_opt = MaybeReadable::read(reader)?;
8361                         let action = Readable::read(reader)?;
8362                         if let Some(ev) = ev_opt {
8363                                 events.push_back((ev, action));
8364                         } else if action.is_some() {
8365                                 return Err(DecodeError::InvalidValue);
8366                         }
8367                 }
8368                 Ok(events)
8369         }
8370 }
8371
8372 impl_writeable_tlv_based_enum!(ChannelShutdownState,
8373         (0, NotShuttingDown) => {},
8374         (2, ShutdownInitiated) => {},
8375         (4, ResolvingHTLCs) => {},
8376         (6, NegotiatingClosingFee) => {},
8377         (8, ShutdownComplete) => {}, ;
8378 );
8379
8380 /// Arguments for the creation of a ChannelManager that are not deserialized.
8381 ///
8382 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
8383 /// is:
8384 /// 1) Deserialize all stored [`ChannelMonitor`]s.
8385 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
8386 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
8387 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
8388 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
8389 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
8390 ///    same way you would handle a [`chain::Filter`] call using
8391 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
8392 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
8393 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
8394 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
8395 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
8396 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
8397 ///    the next step.
8398 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
8399 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
8400 ///
8401 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
8402 /// call any other methods on the newly-deserialized [`ChannelManager`].
8403 ///
8404 /// Note that because some channels may be closed during deserialization, it is critical that you
8405 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
8406 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
8407 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
8408 /// not force-close the same channels but consider them live), you may end up revoking a state for
8409 /// which you've already broadcasted the transaction.
8410 ///
8411 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
8412 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8413 where
8414         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8415         T::Target: BroadcasterInterface,
8416         ES::Target: EntropySource,
8417         NS::Target: NodeSigner,
8418         SP::Target: SignerProvider,
8419         F::Target: FeeEstimator,
8420         R::Target: Router,
8421         L::Target: Logger,
8422 {
8423         /// A cryptographically secure source of entropy.
8424         pub entropy_source: ES,
8425
8426         /// A signer that is able to perform node-scoped cryptographic operations.
8427         pub node_signer: NS,
8428
8429         /// The keys provider which will give us relevant keys. Some keys will be loaded during
8430         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
8431         /// signing data.
8432         pub signer_provider: SP,
8433
8434         /// The fee_estimator for use in the ChannelManager in the future.
8435         ///
8436         /// No calls to the FeeEstimator will be made during deserialization.
8437         pub fee_estimator: F,
8438         /// The chain::Watch for use in the ChannelManager in the future.
8439         ///
8440         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
8441         /// you have deserialized ChannelMonitors separately and will add them to your
8442         /// chain::Watch after deserializing this ChannelManager.
8443         pub chain_monitor: M,
8444
8445         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
8446         /// used to broadcast the latest local commitment transactions of channels which must be
8447         /// force-closed during deserialization.
8448         pub tx_broadcaster: T,
8449         /// The router which will be used in the ChannelManager in the future for finding routes
8450         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
8451         ///
8452         /// No calls to the router will be made during deserialization.
8453         pub router: R,
8454         /// The Logger for use in the ChannelManager and which may be used to log information during
8455         /// deserialization.
8456         pub logger: L,
8457         /// Default settings used for new channels. Any existing channels will continue to use the
8458         /// runtime settings which were stored when the ChannelManager was serialized.
8459         pub default_config: UserConfig,
8460
8461         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
8462         /// value.context.get_funding_txo() should be the key).
8463         ///
8464         /// If a monitor is inconsistent with the channel state during deserialization the channel will
8465         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
8466         /// is true for missing channels as well. If there is a monitor missing for which we find
8467         /// channel data Err(DecodeError::InvalidValue) will be returned.
8468         ///
8469         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
8470         /// this struct.
8471         ///
8472         /// This is not exported to bindings users because we have no HashMap bindings
8473         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>,
8474 }
8475
8476 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8477                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
8478 where
8479         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8480         T::Target: BroadcasterInterface,
8481         ES::Target: EntropySource,
8482         NS::Target: NodeSigner,
8483         SP::Target: SignerProvider,
8484         F::Target: FeeEstimator,
8485         R::Target: Router,
8486         L::Target: Logger,
8487 {
8488         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
8489         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
8490         /// populate a HashMap directly from C.
8491         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,
8492                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::Signer>>) -> Self {
8493                 Self {
8494                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
8495                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
8496                 }
8497         }
8498 }
8499
8500 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
8501 // SipmleArcChannelManager type:
8502 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8503         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
8504 where
8505         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8506         T::Target: BroadcasterInterface,
8507         ES::Target: EntropySource,
8508         NS::Target: NodeSigner,
8509         SP::Target: SignerProvider,
8510         F::Target: FeeEstimator,
8511         R::Target: Router,
8512         L::Target: Logger,
8513 {
8514         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
8515                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
8516                 Ok((blockhash, Arc::new(chan_manager)))
8517         }
8518 }
8519
8520 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8521         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
8522 where
8523         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
8524         T::Target: BroadcasterInterface,
8525         ES::Target: EntropySource,
8526         NS::Target: NodeSigner,
8527         SP::Target: SignerProvider,
8528         F::Target: FeeEstimator,
8529         R::Target: Router,
8530         L::Target: Logger,
8531 {
8532         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
8533                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
8534
8535                 let genesis_hash: BlockHash = Readable::read(reader)?;
8536                 let best_block_height: u32 = Readable::read(reader)?;
8537                 let best_block_hash: BlockHash = Readable::read(reader)?;
8538
8539                 let mut failed_htlcs = Vec::new();
8540
8541                 let channel_count: u64 = Readable::read(reader)?;
8542                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
8543                 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));
8544                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
8545                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
8546                 let mut channel_closures = VecDeque::new();
8547                 let mut close_background_events = Vec::new();
8548                 for _ in 0..channel_count {
8549                         let mut channel: Channel<<SP::Target as SignerProvider>::Signer> = Channel::read(reader, (
8550                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
8551                         ))?;
8552                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
8553                         funding_txo_set.insert(funding_txo.clone());
8554                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
8555                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
8556                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
8557                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
8558                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
8559                                         // But if the channel is behind of the monitor, close the channel:
8560                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
8561                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
8562                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
8563                                                 log_bytes!(channel.context.channel_id()), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
8564                                         let (monitor_update, mut new_failed_htlcs) = channel.context.force_shutdown(true);
8565                                         if let Some((counterparty_node_id, funding_txo, update)) = monitor_update {
8566                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
8567                                                         counterparty_node_id, funding_txo, update
8568                                                 });
8569                                         }
8570                                         failed_htlcs.append(&mut new_failed_htlcs);
8571                                         channel_closures.push_back((events::Event::ChannelClosed {
8572                                                 channel_id: channel.context.channel_id(),
8573                                                 user_channel_id: channel.context.get_user_id(),
8574                                                 reason: ClosureReason::OutdatedChannelManager,
8575                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
8576                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
8577                                         }, None));
8578                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
8579                                                 let mut found_htlc = false;
8580                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
8581                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
8582                                                 }
8583                                                 if !found_htlc {
8584                                                         // If we have some HTLCs in the channel which are not present in the newer
8585                                                         // ChannelMonitor, they have been removed and should be failed back to
8586                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
8587                                                         // were actually claimed we'd have generated and ensured the previous-hop
8588                                                         // claim update ChannelMonitor updates were persisted prior to persising
8589                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
8590                                                         // backwards leg of the HTLC will simply be rejected.
8591                                                         log_info!(args.logger,
8592                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
8593                                                                 log_bytes!(channel.context.channel_id()), log_bytes!(payment_hash.0));
8594                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8595                                                 }
8596                                         }
8597                                 } else {
8598                                         log_info!(args.logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
8599                                                 log_bytes!(channel.context.channel_id()), channel.context.get_latest_monitor_update_id(),
8600                                                 monitor.get_latest_update_id());
8601                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
8602                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8603                                         }
8604                                         if channel.context.is_funding_initiated() {
8605                                                 id_to_peer.insert(channel.context.channel_id(), channel.context.get_counterparty_node_id());
8606                                         }
8607                                         match peer_channels.entry(channel.context.get_counterparty_node_id()) {
8608                                                 hash_map::Entry::Occupied(mut entry) => {
8609                                                         let by_id_map = entry.get_mut();
8610                                                         by_id_map.insert(channel.context.channel_id(), channel);
8611                                                 },
8612                                                 hash_map::Entry::Vacant(entry) => {
8613                                                         let mut by_id_map = HashMap::new();
8614                                                         by_id_map.insert(channel.context.channel_id(), channel);
8615                                                         entry.insert(by_id_map);
8616                                                 }
8617                                         }
8618                                 }
8619                         } else if channel.is_awaiting_initial_mon_persist() {
8620                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
8621                                 // was in-progress, we never broadcasted the funding transaction and can still
8622                                 // safely discard the channel.
8623                                 let _ = channel.context.force_shutdown(false);
8624                                 channel_closures.push_back((events::Event::ChannelClosed {
8625                                         channel_id: channel.context.channel_id(),
8626                                         user_channel_id: channel.context.get_user_id(),
8627                                         reason: ClosureReason::DisconnectedPeer,
8628                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
8629                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
8630                                 }, None));
8631                         } else {
8632                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", log_bytes!(channel.context.channel_id()));
8633                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8634                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8635                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
8636                                 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");
8637                                 return Err(DecodeError::InvalidValue);
8638                         }
8639                 }
8640
8641                 for (funding_txo, _) in args.channel_monitors.iter() {
8642                         if !funding_txo_set.contains(funding_txo) {
8643                                 log_info!(args.logger, "Queueing monitor update to ensure missing channel {} is force closed",
8644                                         log_bytes!(funding_txo.to_channel_id()));
8645                                 let monitor_update = ChannelMonitorUpdate {
8646                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
8647                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
8648                                 };
8649                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, monitor_update)));
8650                         }
8651                 }
8652
8653                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
8654                 let forward_htlcs_count: u64 = Readable::read(reader)?;
8655                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
8656                 for _ in 0..forward_htlcs_count {
8657                         let short_channel_id = Readable::read(reader)?;
8658                         let pending_forwards_count: u64 = Readable::read(reader)?;
8659                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
8660                         for _ in 0..pending_forwards_count {
8661                                 pending_forwards.push(Readable::read(reader)?);
8662                         }
8663                         forward_htlcs.insert(short_channel_id, pending_forwards);
8664                 }
8665
8666                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
8667                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
8668                 for _ in 0..claimable_htlcs_count {
8669                         let payment_hash = Readable::read(reader)?;
8670                         let previous_hops_len: u64 = Readable::read(reader)?;
8671                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
8672                         for _ in 0..previous_hops_len {
8673                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
8674                         }
8675                         claimable_htlcs_list.push((payment_hash, previous_hops));
8676                 }
8677
8678                 let peer_state_from_chans = |channel_by_id| {
8679                         PeerState {
8680                                 channel_by_id,
8681                                 outbound_v1_channel_by_id: HashMap::new(),
8682                                 inbound_v1_channel_by_id: HashMap::new(),
8683                                 inbound_channel_request_by_id: HashMap::new(),
8684                                 latest_features: InitFeatures::empty(),
8685                                 pending_msg_events: Vec::new(),
8686                                 in_flight_monitor_updates: BTreeMap::new(),
8687                                 monitor_update_blocked_actions: BTreeMap::new(),
8688                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
8689                                 is_connected: false,
8690                         }
8691                 };
8692
8693                 let peer_count: u64 = Readable::read(reader)?;
8694                 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>>)>()));
8695                 for _ in 0..peer_count {
8696                         let peer_pubkey = Readable::read(reader)?;
8697                         let peer_chans = peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
8698                         let mut peer_state = peer_state_from_chans(peer_chans);
8699                         peer_state.latest_features = Readable::read(reader)?;
8700                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
8701                 }
8702
8703                 let event_count: u64 = Readable::read(reader)?;
8704                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
8705                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
8706                 for _ in 0..event_count {
8707                         match MaybeReadable::read(reader)? {
8708                                 Some(event) => pending_events_read.push_back((event, None)),
8709                                 None => continue,
8710                         }
8711                 }
8712
8713                 let background_event_count: u64 = Readable::read(reader)?;
8714                 for _ in 0..background_event_count {
8715                         match <u8 as Readable>::read(reader)? {
8716                                 0 => {
8717                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
8718                                         // however we really don't (and never did) need them - we regenerate all
8719                                         // on-startup monitor updates.
8720                                         let _: OutPoint = Readable::read(reader)?;
8721                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
8722                                 }
8723                                 _ => return Err(DecodeError::InvalidValue),
8724                         }
8725                 }
8726
8727                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
8728                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
8729
8730                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
8731                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
8732                 for _ in 0..pending_inbound_payment_count {
8733                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
8734                                 return Err(DecodeError::InvalidValue);
8735                         }
8736                 }
8737
8738                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
8739                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
8740                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
8741                 for _ in 0..pending_outbound_payments_count_compat {
8742                         let session_priv = Readable::read(reader)?;
8743                         let payment = PendingOutboundPayment::Legacy {
8744                                 session_privs: [session_priv].iter().cloned().collect()
8745                         };
8746                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
8747                                 return Err(DecodeError::InvalidValue)
8748                         };
8749                 }
8750
8751                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
8752                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
8753                 let mut pending_outbound_payments = None;
8754                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
8755                 let mut received_network_pubkey: Option<PublicKey> = None;
8756                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
8757                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
8758                 let mut claimable_htlc_purposes = None;
8759                 let mut claimable_htlc_onion_fields = None;
8760                 let mut pending_claiming_payments = Some(HashMap::new());
8761                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
8762                 let mut events_override = None;
8763                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
8764                 read_tlv_fields!(reader, {
8765                         (1, pending_outbound_payments_no_retry, option),
8766                         (2, pending_intercepted_htlcs, option),
8767                         (3, pending_outbound_payments, option),
8768                         (4, pending_claiming_payments, option),
8769                         (5, received_network_pubkey, option),
8770                         (6, monitor_update_blocked_actions_per_peer, option),
8771                         (7, fake_scid_rand_bytes, option),
8772                         (8, events_override, option),
8773                         (9, claimable_htlc_purposes, optional_vec),
8774                         (10, in_flight_monitor_updates, option),
8775                         (11, probing_cookie_secret, option),
8776                         (13, claimable_htlc_onion_fields, optional_vec),
8777                 });
8778                 if fake_scid_rand_bytes.is_none() {
8779                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
8780                 }
8781
8782                 if probing_cookie_secret.is_none() {
8783                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
8784                 }
8785
8786                 if let Some(events) = events_override {
8787                         pending_events_read = events;
8788                 }
8789
8790                 if !channel_closures.is_empty() {
8791                         pending_events_read.append(&mut channel_closures);
8792                 }
8793
8794                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
8795                         pending_outbound_payments = Some(pending_outbound_payments_compat);
8796                 } else if pending_outbound_payments.is_none() {
8797                         let mut outbounds = HashMap::new();
8798                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
8799                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
8800                         }
8801                         pending_outbound_payments = Some(outbounds);
8802                 }
8803                 let pending_outbounds = OutboundPayments {
8804                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
8805                         retry_lock: Mutex::new(())
8806                 };
8807
8808                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
8809                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
8810                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
8811                 // replayed, and for each monitor update we have to replay we have to ensure there's a
8812                 // `ChannelMonitor` for it.
8813                 //
8814                 // In order to do so we first walk all of our live channels (so that we can check their
8815                 // state immediately after doing the update replays, when we have the `update_id`s
8816                 // available) and then walk any remaining in-flight updates.
8817                 //
8818                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
8819                 let mut pending_background_events = Vec::new();
8820                 macro_rules! handle_in_flight_updates {
8821                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
8822                          $monitor: expr, $peer_state: expr, $channel_info_log: expr
8823                         ) => { {
8824                                 let mut max_in_flight_update_id = 0;
8825                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
8826                                 for update in $chan_in_flight_upds.iter() {
8827                                         log_trace!(args.logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
8828                                                 update.update_id, $channel_info_log, log_bytes!($funding_txo.to_channel_id()));
8829                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
8830                                         pending_background_events.push(
8831                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
8832                                                         counterparty_node_id: $counterparty_node_id,
8833                                                         funding_txo: $funding_txo,
8834                                                         update: update.clone(),
8835                                                 });
8836                                 }
8837                                 if $chan_in_flight_upds.is_empty() {
8838                                         // We had some updates to apply, but it turns out they had completed before we
8839                                         // were serialized, we just weren't notified of that. Thus, we may have to run
8840                                         // the completion actions for any monitor updates, but otherwise are done.
8841                                         pending_background_events.push(
8842                                                 BackgroundEvent::MonitorUpdatesComplete {
8843                                                         counterparty_node_id: $counterparty_node_id,
8844                                                         channel_id: $funding_txo.to_channel_id(),
8845                                                 });
8846                                 }
8847                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
8848                                         log_error!(args.logger, "Duplicate in-flight monitor update set for the same channel!");
8849                                         return Err(DecodeError::InvalidValue);
8850                                 }
8851                                 max_in_flight_update_id
8852                         } }
8853                 }
8854
8855                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
8856                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
8857                         let peer_state = &mut *peer_state_lock;
8858                         for (_, chan) in peer_state.channel_by_id.iter() {
8859                                 // Channels that were persisted have to be funded, otherwise they should have been
8860                                 // discarded.
8861                                 let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
8862                                 let monitor = args.channel_monitors.get(&funding_txo)
8863                                         .expect("We already checked for monitor presence when loading channels");
8864                                 let mut max_in_flight_update_id = monitor.get_latest_update_id();
8865                                 if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
8866                                         if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
8867                                                 max_in_flight_update_id = cmp::max(max_in_flight_update_id,
8868                                                         handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
8869                                                                 funding_txo, monitor, peer_state, ""));
8870                                         }
8871                                 }
8872                                 if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
8873                                         // If the channel is ahead of the monitor, return InvalidValue:
8874                                         log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
8875                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
8876                                                 log_bytes!(chan.context.channel_id()), monitor.get_latest_update_id(), max_in_flight_update_id);
8877                                         log_error!(args.logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
8878                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8879                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8880                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
8881                                         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");
8882                                         return Err(DecodeError::InvalidValue);
8883                                 }
8884                         }
8885                 }
8886
8887                 if let Some(in_flight_upds) = in_flight_monitor_updates {
8888                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
8889                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
8890                                         // Now that we've removed all the in-flight monitor updates for channels that are
8891                                         // still open, we need to replay any monitor updates that are for closed channels,
8892                                         // creating the neccessary peer_state entries as we go.
8893                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
8894                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
8895                                         });
8896                                         let mut peer_state = peer_state_mutex.lock().unwrap();
8897                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
8898                                                 funding_txo, monitor, peer_state, "closed ");
8899                                 } else {
8900                                         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!");
8901                                         log_error!(args.logger, " The ChannelMonitor for channel {} is missing.",
8902                                                 log_bytes!(funding_txo.to_channel_id()));
8903                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
8904                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
8905                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
8906                                         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");
8907                                         return Err(DecodeError::InvalidValue);
8908                                 }
8909                         }
8910                 }
8911
8912                 // Note that we have to do the above replays before we push new monitor updates.
8913                 pending_background_events.append(&mut close_background_events);
8914
8915                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
8916                 // should ensure we try them again on the inbound edge. We put them here and do so after we
8917                 // have a fully-constructed `ChannelManager` at the end.
8918                 let mut pending_claims_to_replay = Vec::new();
8919
8920                 {
8921                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
8922                         // ChannelMonitor data for any channels for which we do not have authorative state
8923                         // (i.e. those for which we just force-closed above or we otherwise don't have a
8924                         // corresponding `Channel` at all).
8925                         // This avoids several edge-cases where we would otherwise "forget" about pending
8926                         // payments which are still in-flight via their on-chain state.
8927                         // We only rebuild the pending payments map if we were most recently serialized by
8928                         // 0.0.102+
8929                         for (_, monitor) in args.channel_monitors.iter() {
8930                                 let counterparty_opt = id_to_peer.get(&monitor.get_funding_txo().0.to_channel_id());
8931                                 if counterparty_opt.is_none() {
8932                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
8933                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
8934                                                         if path.hops.is_empty() {
8935                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
8936                                                                 return Err(DecodeError::InvalidValue);
8937                                                         }
8938
8939                                                         let path_amt = path.final_value_msat();
8940                                                         let mut session_priv_bytes = [0; 32];
8941                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
8942                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
8943                                                                 hash_map::Entry::Occupied(mut entry) => {
8944                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
8945                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
8946                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), log_bytes!(htlc.payment_hash.0));
8947                                                                 },
8948                                                                 hash_map::Entry::Vacant(entry) => {
8949                                                                         let path_fee = path.fee_msat();
8950                                                                         entry.insert(PendingOutboundPayment::Retryable {
8951                                                                                 retry_strategy: None,
8952                                                                                 attempts: PaymentAttempts::new(),
8953                                                                                 payment_params: None,
8954                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
8955                                                                                 payment_hash: htlc.payment_hash,
8956                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
8957                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
8958                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
8959                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
8960                                                                                 pending_amt_msat: path_amt,
8961                                                                                 pending_fee_msat: Some(path_fee),
8962                                                                                 total_msat: path_amt,
8963                                                                                 starting_block_height: best_block_height,
8964                                                                         });
8965                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
8966                                                                                 path_amt, log_bytes!(htlc.payment_hash.0),  log_bytes!(session_priv_bytes));
8967                                                                 }
8968                                                         }
8969                                                 }
8970                                         }
8971                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
8972                                                 match htlc_source {
8973                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
8974                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
8975                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
8976                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
8977                                                                 };
8978                                                                 // The ChannelMonitor is now responsible for this HTLC's
8979                                                                 // failure/success and will let us know what its outcome is. If we
8980                                                                 // still have an entry for this HTLC in `forward_htlcs` or
8981                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
8982                                                                 // the monitor was when forwarding the payment.
8983                                                                 forward_htlcs.retain(|_, forwards| {
8984                                                                         forwards.retain(|forward| {
8985                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
8986                                                                                         if pending_forward_matches_htlc(&htlc_info) {
8987                                                                                                 log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
8988                                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
8989                                                                                                 false
8990                                                                                         } else { true }
8991                                                                                 } else { true }
8992                                                                         });
8993                                                                         !forwards.is_empty()
8994                                                                 });
8995                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
8996                                                                         if pending_forward_matches_htlc(&htlc_info) {
8997                                                                                 log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
8998                                                                                         log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
8999                                                                                 pending_events_read.retain(|(event, _)| {
9000                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
9001                                                                                                 intercepted_id != ev_id
9002                                                                                         } else { true }
9003                                                                                 });
9004                                                                                 false
9005                                                                         } else { true }
9006                                                                 });
9007                                                         },
9008                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
9009                                                                 if let Some(preimage) = preimage_opt {
9010                                                                         let pending_events = Mutex::new(pending_events_read);
9011                                                                         // Note that we set `from_onchain` to "false" here,
9012                                                                         // deliberately keeping the pending payment around forever.
9013                                                                         // Given it should only occur when we have a channel we're
9014                                                                         // force-closing for being stale that's okay.
9015                                                                         // The alternative would be to wipe the state when claiming,
9016                                                                         // generating a `PaymentPathSuccessful` event but regenerating
9017                                                                         // it and the `PaymentSent` on every restart until the
9018                                                                         // `ChannelMonitor` is removed.
9019                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv, path, false, &pending_events, &args.logger);
9020                                                                         pending_events_read = pending_events.into_inner().unwrap();
9021                                                                 }
9022                                                         },
9023                                                 }
9024                                         }
9025                                 }
9026
9027                                 // Whether the downstream channel was closed or not, try to re-apply any payment
9028                                 // preimages from it which may be needed in upstream channels for forwarded
9029                                 // payments.
9030                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
9031                                         .into_iter()
9032                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
9033                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
9034                                                         if let Some(payment_preimage) = preimage_opt {
9035                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
9036                                                                         // Check if `counterparty_opt.is_none()` to see if the
9037                                                                         // downstream chan is closed (because we don't have a
9038                                                                         // channel_id -> peer map entry).
9039                                                                         counterparty_opt.is_none(),
9040                                                                         monitor.get_funding_txo().0.to_channel_id()))
9041                                                         } else { None }
9042                                                 } else {
9043                                                         // If it was an outbound payment, we've handled it above - if a preimage
9044                                                         // came in and we persisted the `ChannelManager` we either handled it and
9045                                                         // are good to go or the channel force-closed - we don't have to handle the
9046                                                         // channel still live case here.
9047                                                         None
9048                                                 }
9049                                         });
9050                                 for tuple in outbound_claimed_htlcs_iter {
9051                                         pending_claims_to_replay.push(tuple);
9052                                 }
9053                         }
9054                 }
9055
9056                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
9057                         // If we have pending HTLCs to forward, assume we either dropped a
9058                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
9059                         // shut down before the timer hit. Either way, set the time_forwardable to a small
9060                         // constant as enough time has likely passed that we should simply handle the forwards
9061                         // now, or at least after the user gets a chance to reconnect to our peers.
9062                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
9063                                 time_forwardable: Duration::from_secs(2),
9064                         }, None));
9065                 }
9066
9067                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
9068                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
9069
9070                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
9071                 if let Some(purposes) = claimable_htlc_purposes {
9072                         if purposes.len() != claimable_htlcs_list.len() {
9073                                 return Err(DecodeError::InvalidValue);
9074                         }
9075                         if let Some(onion_fields) = claimable_htlc_onion_fields {
9076                                 if onion_fields.len() != claimable_htlcs_list.len() {
9077                                         return Err(DecodeError::InvalidValue);
9078                                 }
9079                                 for (purpose, (onion, (payment_hash, htlcs))) in
9080                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
9081                                 {
9082                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
9083                                                 purpose, htlcs, onion_fields: onion,
9084                                         });
9085                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
9086                                 }
9087                         } else {
9088                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
9089                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
9090                                                 purpose, htlcs, onion_fields: None,
9091                                         });
9092                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
9093                                 }
9094                         }
9095                 } else {
9096                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
9097                         // include a `_legacy_hop_data` in the `OnionPayload`.
9098                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
9099                                 if htlcs.is_empty() {
9100                                         return Err(DecodeError::InvalidValue);
9101                                 }
9102                                 let purpose = match &htlcs[0].onion_payload {
9103                                         OnionPayload::Invoice { _legacy_hop_data } => {
9104                                                 if let Some(hop_data) = _legacy_hop_data {
9105                                                         events::PaymentPurpose::InvoicePayment {
9106                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
9107                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
9108                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
9109                                                                                 Ok((payment_preimage, _)) => payment_preimage,
9110                                                                                 Err(()) => {
9111                                                                                         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));
9112                                                                                         return Err(DecodeError::InvalidValue);
9113                                                                                 }
9114                                                                         }
9115                                                                 },
9116                                                                 payment_secret: hop_data.payment_secret,
9117                                                         }
9118                                                 } else { return Err(DecodeError::InvalidValue); }
9119                                         },
9120                                         OnionPayload::Spontaneous(payment_preimage) =>
9121                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
9122                                 };
9123                                 claimable_payments.insert(payment_hash, ClaimablePayment {
9124                                         purpose, htlcs, onion_fields: None,
9125                                 });
9126                         }
9127                 }
9128
9129                 let mut secp_ctx = Secp256k1::new();
9130                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
9131
9132                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
9133                         Ok(key) => key,
9134                         Err(()) => return Err(DecodeError::InvalidValue)
9135                 };
9136                 if let Some(network_pubkey) = received_network_pubkey {
9137                         if network_pubkey != our_network_pubkey {
9138                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
9139                                 return Err(DecodeError::InvalidValue);
9140                         }
9141                 }
9142
9143                 let mut outbound_scid_aliases = HashSet::new();
9144                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
9145                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9146                         let peer_state = &mut *peer_state_lock;
9147                         for (chan_id, chan) in peer_state.channel_by_id.iter_mut() {
9148                                 if chan.context.outbound_scid_alias() == 0 {
9149                                         let mut outbound_scid_alias;
9150                                         loop {
9151                                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias
9152                                                         .get_fake_scid(best_block_height, &genesis_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
9153                                                 if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
9154                                         }
9155                                         chan.context.set_outbound_scid_alias(outbound_scid_alias);
9156                                 } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
9157                                         // Note that in rare cases its possible to hit this while reading an older
9158                                         // channel if we just happened to pick a colliding outbound alias above.
9159                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
9160                                         return Err(DecodeError::InvalidValue);
9161                                 }
9162                                 if chan.context.is_usable() {
9163                                         if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
9164                                                 // Note that in rare cases its possible to hit this while reading an older
9165                                                 // channel if we just happened to pick a colliding outbound alias above.
9166                                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
9167                                                 return Err(DecodeError::InvalidValue);
9168                                         }
9169                                 }
9170                         }
9171                 }
9172
9173                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
9174
9175                 for (_, monitor) in args.channel_monitors.iter() {
9176                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
9177                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
9178                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", log_bytes!(payment_hash.0));
9179                                         let mut claimable_amt_msat = 0;
9180                                         let mut receiver_node_id = Some(our_network_pubkey);
9181                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
9182                                         if phantom_shared_secret.is_some() {
9183                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
9184                                                         .expect("Failed to get node_id for phantom node recipient");
9185                                                 receiver_node_id = Some(phantom_pubkey)
9186                                         }
9187                                         for claimable_htlc in &payment.htlcs {
9188                                                 claimable_amt_msat += claimable_htlc.value;
9189
9190                                                 // Add a holding-cell claim of the payment to the Channel, which should be
9191                                                 // applied ~immediately on peer reconnection. Because it won't generate a
9192                                                 // new commitment transaction we can just provide the payment preimage to
9193                                                 // the corresponding ChannelMonitor and nothing else.
9194                                                 //
9195                                                 // We do so directly instead of via the normal ChannelMonitor update
9196                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
9197                                                 // we're not allowed to call it directly yet. Further, we do the update
9198                                                 // without incrementing the ChannelMonitor update ID as there isn't any
9199                                                 // reason to.
9200                                                 // If we were to generate a new ChannelMonitor update ID here and then
9201                                                 // crash before the user finishes block connect we'd end up force-closing
9202                                                 // this channel as well. On the flip side, there's no harm in restarting
9203                                                 // without the new monitor persisted - we'll end up right back here on
9204                                                 // restart.
9205                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
9206                                                 if let Some(peer_node_id) = id_to_peer.get(&previous_channel_id){
9207                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
9208                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9209                                                         let peer_state = &mut *peer_state_lock;
9210                                                         if let Some(channel) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
9211                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
9212                                                         }
9213                                                 }
9214                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
9215                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
9216                                                 }
9217                                         }
9218                                         pending_events_read.push_back((events::Event::PaymentClaimed {
9219                                                 receiver_node_id,
9220                                                 payment_hash,
9221                                                 purpose: payment.purpose,
9222                                                 amount_msat: claimable_amt_msat,
9223                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
9224                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
9225                                         }, None));
9226                                 }
9227                         }
9228                 }
9229
9230                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
9231                         if let Some(peer_state) = per_peer_state.get(&node_id) {
9232                                 for (_, actions) in monitor_update_blocked_actions.iter() {
9233                                         for action in actions.iter() {
9234                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
9235                                                         downstream_counterparty_and_funding_outpoint:
9236                                                                 Some((blocked_node_id, blocked_channel_outpoint, blocking_action)), ..
9237                                                 } = action {
9238                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
9239                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
9240                                                                         .entry(blocked_channel_outpoint.to_channel_id())
9241                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
9242                                                         } else {
9243                                                                 // If the channel we were blocking has closed, we don't need to
9244                                                                 // worry about it - the blocked monitor update should never have
9245                                                                 // been released from the `Channel` object so it can't have
9246                                                                 // completed, and if the channel closed there's no reason to bother
9247                                                                 // anymore.
9248                                                         }
9249                                                 }
9250                                         }
9251                                 }
9252                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
9253                         } else {
9254                                 log_error!(args.logger, "Got blocked actions without a per-peer-state for {}", node_id);
9255                                 return Err(DecodeError::InvalidValue);
9256                         }
9257                 }
9258
9259                 let channel_manager = ChannelManager {
9260                         genesis_hash,
9261                         fee_estimator: bounded_fee_estimator,
9262                         chain_monitor: args.chain_monitor,
9263                         tx_broadcaster: args.tx_broadcaster,
9264                         router: args.router,
9265
9266                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
9267
9268                         inbound_payment_key: expanded_inbound_key,
9269                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
9270                         pending_outbound_payments: pending_outbounds,
9271                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
9272
9273                         forward_htlcs: Mutex::new(forward_htlcs),
9274                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
9275                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
9276                         id_to_peer: Mutex::new(id_to_peer),
9277                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
9278                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
9279
9280                         probing_cookie_secret: probing_cookie_secret.unwrap(),
9281
9282                         our_network_pubkey,
9283                         secp_ctx,
9284
9285                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
9286
9287                         per_peer_state: FairRwLock::new(per_peer_state),
9288
9289                         pending_events: Mutex::new(pending_events_read),
9290                         pending_events_processor: AtomicBool::new(false),
9291                         pending_background_events: Mutex::new(pending_background_events),
9292                         total_consistency_lock: RwLock::new(()),
9293                         background_events_processed_since_startup: AtomicBool::new(false),
9294                         persistence_notifier: Notifier::new(),
9295
9296                         entropy_source: args.entropy_source,
9297                         node_signer: args.node_signer,
9298                         signer_provider: args.signer_provider,
9299
9300                         logger: args.logger,
9301                         default_configuration: args.default_config,
9302                 };
9303
9304                 for htlc_source in failed_htlcs.drain(..) {
9305                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
9306                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
9307                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
9308                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
9309                 }
9310
9311                 for (source, preimage, downstream_value, downstream_closed, downstream_chan_id) in pending_claims_to_replay {
9312                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
9313                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
9314                         // channel is closed we just assume that it probably came from an on-chain claim.
9315                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
9316                                 downstream_closed, downstream_chan_id);
9317                 }
9318
9319                 //TODO: Broadcast channel update for closed channels, but only after we've made a
9320                 //connection or two.
9321
9322                 Ok((best_block_hash.clone(), channel_manager))
9323         }
9324 }
9325
9326 #[cfg(test)]
9327 mod tests {
9328         use bitcoin::hashes::Hash;
9329         use bitcoin::hashes::sha256::Hash as Sha256;
9330         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
9331         use core::sync::atomic::Ordering;
9332         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
9333         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
9334         use crate::ln::channelmanager::{inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
9335         use crate::ln::functional_test_utils::*;
9336         use crate::ln::msgs::{self, ErrorAction};
9337         use crate::ln::msgs::ChannelMessageHandler;
9338         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
9339         use crate::util::errors::APIError;
9340         use crate::util::test_utils;
9341         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
9342         use crate::sign::EntropySource;
9343
9344         #[test]
9345         fn test_notify_limits() {
9346                 // Check that a few cases which don't require the persistence of a new ChannelManager,
9347                 // indeed, do not cause the persistence of a new ChannelManager.
9348                 let chanmon_cfgs = create_chanmon_cfgs(3);
9349                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9350                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9351                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9352
9353                 // All nodes start with a persistable update pending as `create_network` connects each node
9354                 // with all other nodes to make most tests simpler.
9355                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
9356                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
9357                 assert!(nodes[2].node.get_persistable_update_future().poll_is_complete());
9358
9359                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9360
9361                 // We check that the channel info nodes have doesn't change too early, even though we try
9362                 // to connect messages with new values
9363                 chan.0.contents.fee_base_msat *= 2;
9364                 chan.1.contents.fee_base_msat *= 2;
9365                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
9366                         &nodes[1].node.get_our_node_id()).pop().unwrap();
9367                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
9368                         &nodes[0].node.get_our_node_id()).pop().unwrap();
9369
9370                 // The first two nodes (which opened a channel) should now require fresh persistence
9371                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
9372                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
9373                 // ... but the last node should not.
9374                 assert!(!nodes[2].node.get_persistable_update_future().poll_is_complete());
9375                 // After persisting the first two nodes they should no longer need fresh persistence.
9376                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
9377                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
9378
9379                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
9380                 // about the channel.
9381                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
9382                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
9383                 assert!(!nodes[2].node.get_persistable_update_future().poll_is_complete());
9384
9385                 // The nodes which are a party to the channel should also ignore messages from unrelated
9386                 // parties.
9387                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
9388                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
9389                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
9390                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
9391                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
9392                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
9393
9394                 // At this point the channel info given by peers should still be the same.
9395                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
9396                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
9397
9398                 // An earlier version of handle_channel_update didn't check the directionality of the
9399                 // update message and would always update the local fee info, even if our peer was
9400                 // (spuriously) forwarding us our own channel_update.
9401                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
9402                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
9403                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
9404
9405                 // First deliver each peers' own message, checking that the node doesn't need to be
9406                 // persisted and that its channel info remains the same.
9407                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
9408                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
9409                 assert!(!nodes[0].node.get_persistable_update_future().poll_is_complete());
9410                 assert!(!nodes[1].node.get_persistable_update_future().poll_is_complete());
9411                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
9412                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
9413
9414                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
9415                 // the channel info has updated.
9416                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
9417                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
9418                 assert!(nodes[0].node.get_persistable_update_future().poll_is_complete());
9419                 assert!(nodes[1].node.get_persistable_update_future().poll_is_complete());
9420                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
9421                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
9422         }
9423
9424         #[test]
9425         fn test_keysend_dup_hash_partial_mpp() {
9426                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
9427                 // expected.
9428                 let chanmon_cfgs = create_chanmon_cfgs(2);
9429                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9430                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9431                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9432                 create_announced_chan_between_nodes(&nodes, 0, 1);
9433
9434                 // First, send a partial MPP payment.
9435                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
9436                 let mut mpp_route = route.clone();
9437                 mpp_route.paths.push(mpp_route.paths[0].clone());
9438
9439                 let payment_id = PaymentId([42; 32]);
9440                 // Use the utility function send_payment_along_path to send the payment with MPP data which
9441                 // indicates there are more HTLCs coming.
9442                 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.
9443                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9444                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
9445                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
9446                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9447                 check_added_monitors!(nodes[0], 1);
9448                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9449                 assert_eq!(events.len(), 1);
9450                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9451
9452                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
9453                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9454                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9455                 check_added_monitors!(nodes[0], 1);
9456                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9457                 assert_eq!(events.len(), 1);
9458                 let ev = events.drain(..).next().unwrap();
9459                 let payment_event = SendEvent::from_event(ev);
9460                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9461                 check_added_monitors!(nodes[1], 0);
9462                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9463                 expect_pending_htlcs_forwardable!(nodes[1]);
9464                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9465                 check_added_monitors!(nodes[1], 1);
9466                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9467                 assert!(updates.update_add_htlcs.is_empty());
9468                 assert!(updates.update_fulfill_htlcs.is_empty());
9469                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9470                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9471                 assert!(updates.update_fee.is_none());
9472                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9473                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9474                 expect_payment_failed!(nodes[0], our_payment_hash, true);
9475
9476                 // Send the second half of the original MPP payment.
9477                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
9478                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9479                 check_added_monitors!(nodes[0], 1);
9480                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9481                 assert_eq!(events.len(), 1);
9482                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
9483
9484                 // Claim the full MPP payment. Note that we can't use a test utility like
9485                 // claim_funds_along_route because the ordering of the messages causes the second half of the
9486                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
9487                 // lightning messages manually.
9488                 nodes[1].node.claim_funds(payment_preimage);
9489                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
9490                 check_added_monitors!(nodes[1], 2);
9491
9492                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9493                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
9494                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
9495                 check_added_monitors!(nodes[0], 1);
9496                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9497                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
9498                 check_added_monitors!(nodes[1], 1);
9499                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9500                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
9501                 check_added_monitors!(nodes[1], 1);
9502                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
9503                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
9504                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
9505                 check_added_monitors!(nodes[0], 1);
9506                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9507                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
9508                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9509                 check_added_monitors!(nodes[0], 1);
9510                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
9511                 check_added_monitors!(nodes[1], 1);
9512                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
9513                 check_added_monitors!(nodes[1], 1);
9514                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
9515                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
9516                 check_added_monitors!(nodes[0], 1);
9517
9518                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
9519                 // path's success and a PaymentPathSuccessful event for each path's success.
9520                 let events = nodes[0].node.get_and_clear_pending_events();
9521                 assert_eq!(events.len(), 3);
9522                 match events[0] {
9523                         Event::PaymentSent { payment_id: ref id, payment_preimage: ref preimage, payment_hash: ref hash, .. } => {
9524                                 assert_eq!(Some(payment_id), *id);
9525                                 assert_eq!(payment_preimage, *preimage);
9526                                 assert_eq!(our_payment_hash, *hash);
9527                         },
9528                         _ => panic!("Unexpected event"),
9529                 }
9530                 match events[1] {
9531                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
9532                                 assert_eq!(payment_id, *actual_payment_id);
9533                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
9534                                 assert_eq!(route.paths[0], *path);
9535                         },
9536                         _ => panic!("Unexpected event"),
9537                 }
9538                 match events[2] {
9539                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
9540                                 assert_eq!(payment_id, *actual_payment_id);
9541                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
9542                                 assert_eq!(route.paths[0], *path);
9543                         },
9544                         _ => panic!("Unexpected event"),
9545                 }
9546         }
9547
9548         #[test]
9549         fn test_keysend_dup_payment_hash() {
9550                 do_test_keysend_dup_payment_hash(false);
9551                 do_test_keysend_dup_payment_hash(true);
9552         }
9553
9554         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
9555                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
9556                 //      outbound regular payment fails as expected.
9557                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
9558                 //      fails as expected.
9559                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
9560                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
9561                 //      reject MPP keysend payments, since in this case where the payment has no payment
9562                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
9563                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
9564                 //      payment secrets and reject otherwise.
9565                 let chanmon_cfgs = create_chanmon_cfgs(2);
9566                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9567                 let mut mpp_keysend_cfg = test_default_channel_config();
9568                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
9569                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
9570                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9571                 create_announced_chan_between_nodes(&nodes, 0, 1);
9572                 let scorer = test_utils::TestScorer::new();
9573                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9574
9575                 // To start (1), send a regular payment but don't claim it.
9576                 let expected_route = [&nodes[1]];
9577                 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &expected_route, 100_000);
9578
9579                 // Next, attempt a keysend payment and make sure it fails.
9580                 let route_params = RouteParameters {
9581                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
9582                         final_value_msat: 100_000,
9583                 };
9584                 let route = find_route(
9585                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9586                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9587                 ).unwrap();
9588                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9589                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9590                 check_added_monitors!(nodes[0], 1);
9591                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9592                 assert_eq!(events.len(), 1);
9593                 let ev = events.drain(..).next().unwrap();
9594                 let payment_event = SendEvent::from_event(ev);
9595                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9596                 check_added_monitors!(nodes[1], 0);
9597                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9598                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
9599                 // fails), the second will process the resulting failure and fail the HTLC backward
9600                 expect_pending_htlcs_forwardable!(nodes[1]);
9601                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9602                 check_added_monitors!(nodes[1], 1);
9603                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9604                 assert!(updates.update_add_htlcs.is_empty());
9605                 assert!(updates.update_fulfill_htlcs.is_empty());
9606                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9607                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9608                 assert!(updates.update_fee.is_none());
9609                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9610                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9611                 expect_payment_failed!(nodes[0], payment_hash, true);
9612
9613                 // Finally, claim the original payment.
9614                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9615
9616                 // To start (2), send a keysend payment but don't claim it.
9617                 let payment_preimage = PaymentPreimage([42; 32]);
9618                 let route = find_route(
9619                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9620                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9621                 ).unwrap();
9622                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9623                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
9624                 check_added_monitors!(nodes[0], 1);
9625                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9626                 assert_eq!(events.len(), 1);
9627                 let event = events.pop().unwrap();
9628                 let path = vec![&nodes[1]];
9629                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
9630
9631                 // Next, attempt a regular payment and make sure it fails.
9632                 let payment_secret = PaymentSecret([43; 32]);
9633                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9634                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9635                 check_added_monitors!(nodes[0], 1);
9636                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9637                 assert_eq!(events.len(), 1);
9638                 let ev = events.drain(..).next().unwrap();
9639                 let payment_event = SendEvent::from_event(ev);
9640                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9641                 check_added_monitors!(nodes[1], 0);
9642                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9643                 expect_pending_htlcs_forwardable!(nodes[1]);
9644                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9645                 check_added_monitors!(nodes[1], 1);
9646                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9647                 assert!(updates.update_add_htlcs.is_empty());
9648                 assert!(updates.update_fulfill_htlcs.is_empty());
9649                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9650                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9651                 assert!(updates.update_fee.is_none());
9652                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9653                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9654                 expect_payment_failed!(nodes[0], payment_hash, true);
9655
9656                 // Finally, succeed the keysend payment.
9657                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9658
9659                 // To start (3), send a keysend payment but don't claim it.
9660                 let payment_id_1 = PaymentId([44; 32]);
9661                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9662                         RecipientOnionFields::spontaneous_empty(), payment_id_1).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 event = events.pop().unwrap();
9667                 let path = vec![&nodes[1]];
9668                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
9669
9670                 // Next, attempt a keysend payment and make sure it fails.
9671                 let route_params = RouteParameters {
9672                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
9673                         final_value_msat: 100_000,
9674                 };
9675                 let route = find_route(
9676                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
9677                         None, nodes[0].logger, &scorer, &(), &random_seed_bytes
9678                 ).unwrap();
9679                 let payment_id_2 = PaymentId([45; 32]);
9680                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
9681                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
9682                 check_added_monitors!(nodes[0], 1);
9683                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9684                 assert_eq!(events.len(), 1);
9685                 let ev = events.drain(..).next().unwrap();
9686                 let payment_event = SendEvent::from_event(ev);
9687                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9688                 check_added_monitors!(nodes[1], 0);
9689                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9690                 expect_pending_htlcs_forwardable!(nodes[1]);
9691                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9692                 check_added_monitors!(nodes[1], 1);
9693                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9694                 assert!(updates.update_add_htlcs.is_empty());
9695                 assert!(updates.update_fulfill_htlcs.is_empty());
9696                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9697                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9698                 assert!(updates.update_fee.is_none());
9699                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9700                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9701                 expect_payment_failed!(nodes[0], payment_hash, true);
9702
9703                 // Finally, claim the original payment.
9704                 claim_payment(&nodes[0], &expected_route, payment_preimage);
9705         }
9706
9707         #[test]
9708         fn test_keysend_hash_mismatch() {
9709                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
9710                 // preimage doesn't match the msg's payment hash.
9711                 let chanmon_cfgs = create_chanmon_cfgs(2);
9712                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9713                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9714                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9715
9716                 let payer_pubkey = nodes[0].node.get_our_node_id();
9717                 let payee_pubkey = nodes[1].node.get_our_node_id();
9718
9719                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9720                 let route_params = RouteParameters {
9721                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9722                         final_value_msat: 10_000,
9723                 };
9724                 let network_graph = nodes[0].network_graph.clone();
9725                 let first_hops = nodes[0].node.list_usable_channels();
9726                 let scorer = test_utils::TestScorer::new();
9727                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9728                 let route = find_route(
9729                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9730                         nodes[0].logger, &scorer, &(), &random_seed_bytes
9731                 ).unwrap();
9732
9733                 let test_preimage = PaymentPreimage([42; 32]);
9734                 let mismatch_payment_hash = PaymentHash([43; 32]);
9735                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
9736                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
9737                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
9738                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
9739                 check_added_monitors!(nodes[0], 1);
9740
9741                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9742                 assert_eq!(updates.update_add_htlcs.len(), 1);
9743                 assert!(updates.update_fulfill_htlcs.is_empty());
9744                 assert!(updates.update_fail_htlcs.is_empty());
9745                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9746                 assert!(updates.update_fee.is_none());
9747                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
9748
9749                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
9750         }
9751
9752         #[test]
9753         fn test_keysend_msg_with_secret_err() {
9754                 // Test that we error as expected if we receive a keysend payment that includes a payment
9755                 // secret when we don't support MPP keysend.
9756                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
9757                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
9758                 let chanmon_cfgs = create_chanmon_cfgs(2);
9759                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9760                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
9761                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9762
9763                 let payer_pubkey = nodes[0].node.get_our_node_id();
9764                 let payee_pubkey = nodes[1].node.get_our_node_id();
9765
9766                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9767                 let route_params = RouteParameters {
9768                         payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9769                         final_value_msat: 10_000,
9770                 };
9771                 let network_graph = nodes[0].network_graph.clone();
9772                 let first_hops = nodes[0].node.list_usable_channels();
9773                 let scorer = test_utils::TestScorer::new();
9774                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9775                 let route = find_route(
9776                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9777                         nodes[0].logger, &scorer, &(), &random_seed_bytes
9778                 ).unwrap();
9779
9780                 let test_preimage = PaymentPreimage([42; 32]);
9781                 let test_secret = PaymentSecret([43; 32]);
9782                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
9783                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
9784                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
9785                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
9786                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
9787                         PaymentId(payment_hash.0), None, session_privs).unwrap();
9788                 check_added_monitors!(nodes[0], 1);
9789
9790                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9791                 assert_eq!(updates.update_add_htlcs.len(), 1);
9792                 assert!(updates.update_fulfill_htlcs.is_empty());
9793                 assert!(updates.update_fail_htlcs.is_empty());
9794                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9795                 assert!(updates.update_fee.is_none());
9796                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
9797
9798                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
9799         }
9800
9801         #[test]
9802         fn test_multi_hop_missing_secret() {
9803                 let chanmon_cfgs = create_chanmon_cfgs(4);
9804                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9805                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9806                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9807
9808                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
9809                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
9810                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
9811                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
9812
9813                 // Marshall an MPP route.
9814                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
9815                 let path = route.paths[0].clone();
9816                 route.paths.push(path);
9817                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
9818                 route.paths[0].hops[0].short_channel_id = chan_1_id;
9819                 route.paths[0].hops[1].short_channel_id = chan_3_id;
9820                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
9821                 route.paths[1].hops[0].short_channel_id = chan_2_id;
9822                 route.paths[1].hops[1].short_channel_id = chan_4_id;
9823
9824                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
9825                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
9826                 .unwrap_err() {
9827                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
9828                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
9829                         },
9830                         _ => panic!("unexpected error")
9831                 }
9832         }
9833
9834         #[test]
9835         fn test_drop_disconnected_peers_when_removing_channels() {
9836                 let chanmon_cfgs = create_chanmon_cfgs(2);
9837                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9838                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9839                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9840
9841                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9842
9843                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9844                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9845
9846                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
9847                 check_closed_broadcast!(nodes[0], true);
9848                 check_added_monitors!(nodes[0], 1);
9849                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
9850
9851                 {
9852                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
9853                         // disconnected and the channel between has been force closed.
9854                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9855                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
9856                         assert_eq!(nodes_0_per_peer_state.len(), 1);
9857                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
9858                 }
9859
9860                 nodes[0].node.timer_tick_occurred();
9861
9862                 {
9863                         // Assert that nodes[1] has now been removed.
9864                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
9865                 }
9866         }
9867
9868         #[test]
9869         fn bad_inbound_payment_hash() {
9870                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
9871                 let chanmon_cfgs = create_chanmon_cfgs(2);
9872                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9873                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9874                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9875
9876                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
9877                 let payment_data = msgs::FinalOnionHopData {
9878                         payment_secret,
9879                         total_msat: 100_000,
9880                 };
9881
9882                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
9883                 // payment verification fails as expected.
9884                 let mut bad_payment_hash = payment_hash.clone();
9885                 bad_payment_hash.0[0] += 1;
9886                 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) {
9887                         Ok(_) => panic!("Unexpected ok"),
9888                         Err(()) => {
9889                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
9890                         }
9891                 }
9892
9893                 // Check that using the original payment hash succeeds.
9894                 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());
9895         }
9896
9897         #[test]
9898         fn test_id_to_peer_coverage() {
9899                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
9900                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
9901                 // the channel is successfully closed.
9902                 let chanmon_cfgs = create_chanmon_cfgs(2);
9903                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9904                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9905                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9906
9907                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9908                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9909                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9910                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9911                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9912
9913                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9914                 let channel_id = &tx.txid().into_inner();
9915                 {
9916                         // Ensure that the `id_to_peer` map is empty until either party has received the
9917                         // funding transaction, and have the real `channel_id`.
9918                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
9919                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9920                 }
9921
9922                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9923                 {
9924                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
9925                         // as it has the funding transaction.
9926                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9927                         assert_eq!(nodes_0_lock.len(), 1);
9928                         assert!(nodes_0_lock.contains_key(channel_id));
9929                 }
9930
9931                 assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
9932
9933                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9934
9935                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9936                 {
9937                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9938                         assert_eq!(nodes_0_lock.len(), 1);
9939                         assert!(nodes_0_lock.contains_key(channel_id));
9940                 }
9941                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9942
9943                 {
9944                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
9945                         // as it has the funding transaction.
9946                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9947                         assert_eq!(nodes_1_lock.len(), 1);
9948                         assert!(nodes_1_lock.contains_key(channel_id));
9949                 }
9950                 check_added_monitors!(nodes[1], 1);
9951                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9952                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9953                 check_added_monitors!(nodes[0], 1);
9954                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9955                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9956                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9957                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
9958
9959                 nodes[0].node.close_channel(channel_id, &nodes[1].node.get_our_node_id()).unwrap();
9960                 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()));
9961                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
9962                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
9963
9964                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
9965                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
9966                 {
9967                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
9968                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
9969                         // fee for the closing transaction has been negotiated and the parties has the other
9970                         // party's signature for the fee negotiated closing transaction.)
9971                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
9972                         assert_eq!(nodes_0_lock.len(), 1);
9973                         assert!(nodes_0_lock.contains_key(channel_id));
9974                 }
9975
9976                 {
9977                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
9978                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
9979                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
9980                         // kept in the `nodes[1]`'s `id_to_peer` map.
9981                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9982                         assert_eq!(nodes_1_lock.len(), 1);
9983                         assert!(nodes_1_lock.contains_key(channel_id));
9984                 }
9985
9986                 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()));
9987                 {
9988                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
9989                         // therefore has all it needs to fully close the channel (both signatures for the
9990                         // closing transaction).
9991                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
9992                         // fully closed by `nodes[0]`.
9993                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
9994
9995                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
9996                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
9997                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
9998                         assert_eq!(nodes_1_lock.len(), 1);
9999                         assert!(nodes_1_lock.contains_key(channel_id));
10000                 }
10001
10002                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
10003
10004                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
10005                 {
10006                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
10007                         // they both have everything required to fully close the channel.
10008                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
10009                 }
10010                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
10011
10012                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
10013                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
10014         }
10015
10016         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
10017                 let expected_message = format!("Not connected to node: {}", expected_public_key);
10018                 check_api_error_message(expected_message, res_err)
10019         }
10020
10021         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
10022                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
10023                 check_api_error_message(expected_message, res_err)
10024         }
10025
10026         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
10027                 match res_err {
10028                         Err(APIError::APIMisuseError { err }) => {
10029                                 assert_eq!(err, expected_err_message);
10030                         },
10031                         Err(APIError::ChannelUnavailable { err }) => {
10032                                 assert_eq!(err, expected_err_message);
10033                         },
10034                         Ok(_) => panic!("Unexpected Ok"),
10035                         Err(_) => panic!("Unexpected Error"),
10036                 }
10037         }
10038
10039         #[test]
10040         fn test_api_calls_with_unkown_counterparty_node() {
10041                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
10042                 // expected if the `counterparty_node_id` is an unkown peer in the
10043                 // `ChannelManager::per_peer_state` map.
10044                 let chanmon_cfg = create_chanmon_cfgs(2);
10045                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
10046                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
10047                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
10048
10049                 // Dummy values
10050                 let channel_id = [4; 32];
10051                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
10052                 let intercept_id = InterceptId([0; 32]);
10053
10054                 // Test the API functions.
10055                 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);
10056
10057                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
10058
10059                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
10060
10061                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
10062
10063                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
10064
10065                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
10066
10067                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
10068         }
10069
10070         #[test]
10071         fn test_connection_limiting() {
10072                 // Test that we limit un-channel'd peers and un-funded channels properly.
10073                 let chanmon_cfgs = create_chanmon_cfgs(2);
10074                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10075                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10076                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10077
10078                 // Note that create_network connects the nodes together for us
10079
10080                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10081                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10082
10083                 let mut funding_tx = None;
10084                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
10085                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10086                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10087
10088                         if idx == 0 {
10089                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
10090                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
10091                                 funding_tx = Some(tx.clone());
10092                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
10093                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10094
10095                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
10096                                 check_added_monitors!(nodes[1], 1);
10097                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10098
10099                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10100
10101                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
10102                                 check_added_monitors!(nodes[0], 1);
10103                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
10104                         }
10105                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10106                 }
10107
10108                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
10109                 open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10110                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10111                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
10112                         open_channel_msg.temporary_channel_id);
10113
10114                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
10115                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
10116                 // limit.
10117                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
10118                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
10119                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
10120                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
10121                         peer_pks.push(random_pk);
10122                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
10123                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10124                         }, true).unwrap();
10125                 }
10126                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
10127                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
10128                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
10129                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10130                 }, true).unwrap_err();
10131
10132                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
10133                 // them if we have too many un-channel'd peers.
10134                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10135                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
10136                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
10137                 for ev in chan_closed_events {
10138                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
10139                 }
10140                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
10141                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10142                 }, true).unwrap();
10143                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10144                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10145                 }, true).unwrap_err();
10146
10147                 // but of course if the connection is outbound its allowed...
10148                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10149                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10150                 }, false).unwrap();
10151                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10152
10153                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
10154                 // Even though we accept one more connection from new peers, we won't actually let them
10155                 // open channels.
10156                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
10157                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
10158                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
10159                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
10160                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10161                 }
10162                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10163                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
10164                         open_channel_msg.temporary_channel_id);
10165
10166                 // Of course, however, outbound channels are always allowed
10167                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None).unwrap();
10168                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
10169
10170                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
10171                 // "protected" and can connect again.
10172                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
10173                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10174                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10175                 }, true).unwrap();
10176                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
10177
10178                 // Further, because the first channel was funded, we can open another channel with
10179                 // last_random_pk.
10180                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10181                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
10182         }
10183
10184         #[test]
10185         fn test_outbound_chans_unlimited() {
10186                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
10187                 let chanmon_cfgs = create_chanmon_cfgs(2);
10188                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10189                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10190                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10191
10192                 // Note that create_network connects the nodes together for us
10193
10194                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10195                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10196
10197                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
10198                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10199                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10200                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10201                 }
10202
10203                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
10204                 // rejected.
10205                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10206                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
10207                         open_channel_msg.temporary_channel_id);
10208
10209                 // but we can still open an outbound channel.
10210                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10211                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
10212
10213                 // but even with such an outbound channel, additional inbound channels will still fail.
10214                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10215                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
10216                         open_channel_msg.temporary_channel_id);
10217         }
10218
10219         #[test]
10220         fn test_0conf_limiting() {
10221                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
10222                 // flag set and (sometimes) accept channels as 0conf.
10223                 let chanmon_cfgs = create_chanmon_cfgs(2);
10224                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10225                 let mut settings = test_default_channel_config();
10226                 settings.manually_accept_inbound_channels = true;
10227                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
10228                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10229
10230                 // Note that create_network connects the nodes together for us
10231
10232                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10233                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10234
10235                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
10236                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
10237                         let 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(&random_pk, &msgs::Init {
10240                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10241                         }, true).unwrap();
10242
10243                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
10244                         let events = nodes[1].node.get_and_clear_pending_events();
10245                         match events[0] {
10246                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
10247                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
10248                                 }
10249                                 _ => panic!("Unexpected event"),
10250                         }
10251                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
10252                         open_channel_msg.temporary_channel_id = nodes[0].keys_manager.get_secure_random_bytes();
10253                 }
10254
10255                 // If we try to accept a channel from another peer non-0conf it will fail.
10256                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
10257                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
10258                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
10259                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10260                 }, true).unwrap();
10261                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10262                 let events = nodes[1].node.get_and_clear_pending_events();
10263                 match events[0] {
10264                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
10265                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
10266                                         Err(APIError::APIMisuseError { err }) =>
10267                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
10268                                         _ => panic!(),
10269                                 }
10270                         }
10271                         _ => panic!("Unexpected event"),
10272                 }
10273                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
10274                         open_channel_msg.temporary_channel_id);
10275
10276                 // ...however if we accept the same channel 0conf it should work just fine.
10277                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
10278                 let events = nodes[1].node.get_and_clear_pending_events();
10279                 match events[0] {
10280                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
10281                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
10282                         }
10283                         _ => panic!("Unexpected event"),
10284                 }
10285                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
10286         }
10287
10288         #[test]
10289         fn reject_excessively_underpaying_htlcs() {
10290                 let chanmon_cfg = create_chanmon_cfgs(1);
10291                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
10292                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
10293                 let node = create_network(1, &node_cfg, &node_chanmgr);
10294                 let sender_intended_amt_msat = 100;
10295                 let extra_fee_msat = 10;
10296                 let hop_data = msgs::InboundOnionPayload::Receive {
10297                         amt_msat: 100,
10298                         outgoing_cltv_value: 42,
10299                         payment_metadata: None,
10300                         keysend_preimage: None,
10301                         payment_data: Some(msgs::FinalOnionHopData {
10302                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
10303                         }),
10304                         custom_tlvs: Vec::new(),
10305                 };
10306                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
10307                 // intended amount, we fail the payment.
10308                 if let Err(crate::ln::channelmanager::InboundOnionErr { err_code, .. }) =
10309                         node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
10310                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat))
10311                 {
10312                         assert_eq!(err_code, 19);
10313                 } else { panic!(); }
10314
10315                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
10316                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
10317                         amt_msat: 100,
10318                         outgoing_cltv_value: 42,
10319                         payment_metadata: None,
10320                         keysend_preimage: None,
10321                         payment_data: Some(msgs::FinalOnionHopData {
10322                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
10323                         }),
10324                         custom_tlvs: Vec::new(),
10325                 };
10326                 assert!(node[0].node.construct_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
10327                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat)).is_ok());
10328         }
10329
10330         #[test]
10331         fn test_inbound_anchors_manual_acceptance() {
10332                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
10333                 // flag set and (sometimes) accept channels as 0conf.
10334                 let mut anchors_cfg = test_default_channel_config();
10335                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
10336
10337                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
10338                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
10339
10340                 let chanmon_cfgs = create_chanmon_cfgs(3);
10341                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10342                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
10343                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
10344                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10345
10346                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10347                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10348
10349                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10350                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
10351                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10352                 match &msg_events[0] {
10353                         MessageSendEvent::HandleError { node_id, action } => {
10354                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10355                                 match action {
10356                                         ErrorAction::SendErrorMessage { msg } =>
10357                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
10358                                         _ => panic!("Unexpected error action"),
10359                                 }
10360                         }
10361                         _ => panic!("Unexpected event"),
10362                 }
10363
10364                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10365                 let events = nodes[2].node.get_and_clear_pending_events();
10366                 match events[0] {
10367                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
10368                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
10369                         _ => panic!("Unexpected event"),
10370                 }
10371                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10372         }
10373
10374         #[test]
10375         fn test_anchors_zero_fee_htlc_tx_fallback() {
10376                 // Tests that if both nodes support anchors, but the remote node does not want to accept
10377                 // anchor channels at the moment, an error it sent to the local node such that it can retry
10378                 // the channel without the anchors feature.
10379                 let chanmon_cfgs = create_chanmon_cfgs(2);
10380                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10381                 let mut anchors_config = test_default_channel_config();
10382                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
10383                 anchors_config.manually_accept_inbound_channels = true;
10384                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
10385                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10386
10387                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None).unwrap();
10388                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10389                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
10390
10391                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
10392                 let events = nodes[1].node.get_and_clear_pending_events();
10393                 match events[0] {
10394                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
10395                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
10396                         }
10397                         _ => panic!("Unexpected event"),
10398                 }
10399
10400                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
10401                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
10402
10403                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10404                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
10405
10406                 // Since nodes[1] should not have accepted the channel, it should
10407                 // not have generated any events.
10408                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
10409         }
10410
10411         #[test]
10412         fn test_update_channel_config() {
10413                 let chanmon_cfg = create_chanmon_cfgs(2);
10414                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
10415                 let mut user_config = test_default_channel_config();
10416                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
10417                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
10418                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
10419                 let channel = &nodes[0].node.list_channels()[0];
10420
10421                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
10422                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10423                 assert_eq!(events.len(), 0);
10424
10425                 user_config.channel_config.forwarding_fee_base_msat += 10;
10426                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
10427                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
10428                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10429                 assert_eq!(events.len(), 1);
10430                 match &events[0] {
10431                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10432                         _ => panic!("expected BroadcastChannelUpdate event"),
10433                 }
10434
10435                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
10436                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10437                 assert_eq!(events.len(), 0);
10438
10439                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
10440                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
10441                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
10442                         ..Default::default()
10443                 }).unwrap();
10444                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
10445                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10446                 assert_eq!(events.len(), 1);
10447                 match &events[0] {
10448                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10449                         _ => panic!("expected BroadcastChannelUpdate event"),
10450                 }
10451
10452                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
10453                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
10454                         forwarding_fee_proportional_millionths: Some(new_fee),
10455                         ..Default::default()
10456                 }).unwrap();
10457                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
10458                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
10459                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10460                 assert_eq!(events.len(), 1);
10461                 match &events[0] {
10462                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
10463                         _ => panic!("expected BroadcastChannelUpdate event"),
10464                 }
10465
10466                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
10467                 // should be applied to ensure update atomicity as specified in the API docs.
10468                 let bad_channel_id = [10; 32];
10469                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
10470                 let new_fee = current_fee + 100;
10471                 assert!(
10472                         matches!(
10473                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
10474                                         forwarding_fee_proportional_millionths: Some(new_fee),
10475                                         ..Default::default()
10476                                 }),
10477                                 Err(APIError::ChannelUnavailable { err: _ }),
10478                         )
10479                 );
10480                 // Check that the fee hasn't changed for the channel that exists.
10481                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
10482                 let events = nodes[0].node.get_and_clear_pending_msg_events();
10483                 assert_eq!(events.len(), 0);
10484         }
10485 }
10486
10487 #[cfg(ldk_bench)]
10488 pub mod bench {
10489         use crate::chain::Listen;
10490         use crate::chain::chainmonitor::{ChainMonitor, Persist};
10491         use crate::sign::{KeysManager, InMemorySigner};
10492         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
10493         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
10494         use crate::ln::functional_test_utils::*;
10495         use crate::ln::msgs::{ChannelMessageHandler, Init};
10496         use crate::routing::gossip::NetworkGraph;
10497         use crate::routing::router::{PaymentParameters, RouteParameters};
10498         use crate::util::test_utils;
10499         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
10500
10501         use bitcoin::hashes::Hash;
10502         use bitcoin::hashes::sha256::Hash as Sha256;
10503         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
10504
10505         use crate::sync::{Arc, Mutex};
10506
10507         use criterion::Criterion;
10508
10509         type Manager<'a, P> = ChannelManager<
10510                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
10511                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
10512                         &'a test_utils::TestLogger, &'a P>,
10513                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
10514                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
10515                 &'a test_utils::TestLogger>;
10516
10517         struct ANodeHolder<'a, P: Persist<InMemorySigner>> {
10518                 node: &'a Manager<'a, P>,
10519         }
10520         impl<'a, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'a, P> {
10521                 type CM = Manager<'a, P>;
10522                 #[inline]
10523                 fn node(&self) -> &Manager<'a, P> { self.node }
10524                 #[inline]
10525                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
10526         }
10527
10528         pub fn bench_sends(bench: &mut Criterion) {
10529                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
10530         }
10531
10532         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
10533                 // Do a simple benchmark of sending a payment back and forth between two nodes.
10534                 // Note that this is unrealistic as each payment send will require at least two fsync
10535                 // calls per node.
10536                 let network = bitcoin::Network::Testnet;
10537                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
10538
10539                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
10540                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
10541                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
10542                 let scorer = Mutex::new(test_utils::TestScorer::new());
10543                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &scorer);
10544
10545                 let mut config: UserConfig = Default::default();
10546                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
10547                 config.channel_handshake_config.minimum_depth = 1;
10548
10549                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
10550                 let seed_a = [1u8; 32];
10551                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
10552                 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 {
10553                         network,
10554                         best_block: BestBlock::from_network(network),
10555                 }, genesis_block.header.time);
10556                 let node_a_holder = ANodeHolder { node: &node_a };
10557
10558                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
10559                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
10560                 let seed_b = [2u8; 32];
10561                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
10562                 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 {
10563                         network,
10564                         best_block: BestBlock::from_network(network),
10565                 }, genesis_block.header.time);
10566                 let node_b_holder = ANodeHolder { node: &node_b };
10567
10568                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
10569                         features: node_b.init_features(), networks: None, remote_network_address: None
10570                 }, true).unwrap();
10571                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
10572                         features: node_a.init_features(), networks: None, remote_network_address: None
10573                 }, false).unwrap();
10574                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
10575                 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()));
10576                 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()));
10577
10578                 let tx;
10579                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
10580                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
10581                                 value: 8_000_000, script_pubkey: output_script,
10582                         }]};
10583                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
10584                 } else { panic!(); }
10585
10586                 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()));
10587                 let events_b = node_b.get_and_clear_pending_events();
10588                 assert_eq!(events_b.len(), 1);
10589                 match events_b[0] {
10590                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
10591                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
10592                         },
10593                         _ => panic!("Unexpected event"),
10594                 }
10595
10596                 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()));
10597                 let events_a = node_a.get_and_clear_pending_events();
10598                 assert_eq!(events_a.len(), 1);
10599                 match events_a[0] {
10600                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
10601                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
10602                         },
10603                         _ => panic!("Unexpected event"),
10604                 }
10605
10606                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
10607
10608                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
10609                 Listen::block_connected(&node_a, &block, 1);
10610                 Listen::block_connected(&node_b, &block, 1);
10611
10612                 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()));
10613                 let msg_events = node_a.get_and_clear_pending_msg_events();
10614                 assert_eq!(msg_events.len(), 2);
10615                 match msg_events[0] {
10616                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
10617                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
10618                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
10619                         },
10620                         _ => panic!(),
10621                 }
10622                 match msg_events[1] {
10623                         MessageSendEvent::SendChannelUpdate { .. } => {},
10624                         _ => panic!(),
10625                 }
10626
10627                 let events_a = node_a.get_and_clear_pending_events();
10628                 assert_eq!(events_a.len(), 1);
10629                 match events_a[0] {
10630                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
10631                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
10632                         },
10633                         _ => panic!("Unexpected event"),
10634                 }
10635
10636                 let events_b = node_b.get_and_clear_pending_events();
10637                 assert_eq!(events_b.len(), 1);
10638                 match events_b[0] {
10639                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
10640                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
10641                         },
10642                         _ => panic!("Unexpected event"),
10643                 }
10644
10645                 let mut payment_count: u64 = 0;
10646                 macro_rules! send_payment {
10647                         ($node_a: expr, $node_b: expr) => {
10648                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
10649                                         .with_bolt11_features($node_b.invoice_features()).unwrap();
10650                                 let mut payment_preimage = PaymentPreimage([0; 32]);
10651                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
10652                                 payment_count += 1;
10653                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
10654                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
10655
10656                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
10657                                         PaymentId(payment_hash.0), RouteParameters {
10658                                                 payment_params, final_value_msat: 10_000,
10659                                         }, Retry::Attempts(0)).unwrap();
10660                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
10661                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
10662                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
10663                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
10664                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
10665                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
10666                                 $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()));
10667
10668                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
10669                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
10670                                 $node_b.claim_funds(payment_preimage);
10671                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
10672
10673                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
10674                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
10675                                                 assert_eq!(node_id, $node_a.get_our_node_id());
10676                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10677                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
10678                                         },
10679                                         _ => panic!("Failed to generate claim event"),
10680                                 }
10681
10682                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
10683                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
10684                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
10685                                 $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()));
10686
10687                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
10688                         }
10689                 }
10690
10691                 bench.bench_function(bench_name, |b| b.iter(|| {
10692                         send_payment!(node_a, node_b);
10693                         send_payment!(node_b, node_a);
10694                 }));
10695         }
10696 }