03a150e4fe208493dea2480abeba968b5b79a877
[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 [`find_route`] 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 //! [`find_route`]: crate::routing::router::find_route
21
22 use bitcoin::blockdata::block::BlockHeader;
23 use bitcoin::blockdata::transaction::Transaction;
24 use bitcoin::blockdata::constants::genesis_block;
25 use bitcoin::network::constants::Network;
26
27 use bitcoin::hashes::Hash;
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
30 use bitcoin::hash_types::{BlockHash, Txid};
31
32 use bitcoin::secp256k1::{SecretKey,PublicKey};
33 use bitcoin::secp256k1::Secp256k1;
34 use bitcoin::secp256k1::ecdh::SharedSecret;
35 use bitcoin::{LockTime, secp256k1, Sequence};
36
37 use crate::chain;
38 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
39 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
40 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};
41 use crate::chain::transaction::{OutPoint, TransactionData};
42 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
43 // construct one themselves.
44 use crate::ln::{inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
45 use crate::ln::channel::{Channel, ChannelError, ChannelUpdateStatus, UpdateFulfillCommitFetch};
46 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
47 #[cfg(any(feature = "_test_utils", test))]
48 use crate::ln::features::InvoiceFeatures;
49 use crate::routing::gossip::NetworkGraph;
50 use crate::routing::router::{DefaultRouter, InFlightHtlcs, PaymentParameters, Route, RouteHop, RoutePath, Router};
51 use crate::routing::scoring::ProbabilisticScorer;
52 use crate::ln::msgs;
53 use crate::ln::onion_utils;
54 use crate::ln::onion_utils::HTLCFailReason;
55 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT};
56 #[cfg(test)]
57 use crate::ln::outbound_payment;
58 use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment};
59 use crate::ln::wire::Encode;
60 use crate::chain::keysinterface::{EntropySource, KeysInterface, KeysManager, NodeSigner, Recipient, Sign, SignerProvider};
61 use crate::util::config::{UserConfig, ChannelConfig};
62 use crate::util::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
63 use crate::util::events;
64 use crate::util::wakers::{Future, Notifier};
65 use crate::util::scid_utils::fake_scid;
66 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
67 use crate::util::logger::{Level, Logger};
68 use crate::util::errors::APIError;
69
70 use crate::io;
71 use crate::prelude::*;
72 use core::{cmp, mem};
73 use core::cell::RefCell;
74 use crate::io::Read;
75 use crate::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard, FairRwLock};
76 use core::sync::atomic::{AtomicUsize, Ordering};
77 use core::time::Duration;
78 use core::ops::Deref;
79
80 // Re-export this for use in the public API.
81 pub use crate::ln::outbound_payment::PaymentSendFailure;
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                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
111                 phantom_shared_secret: Option<[u8; 32]>,
112         },
113         ReceiveKeysend {
114                 payment_preimage: PaymentPreimage,
115                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
116         },
117 }
118
119 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
120 pub(super) struct PendingHTLCInfo {
121         pub(super) routing: PendingHTLCRouting,
122         pub(super) incoming_shared_secret: [u8; 32],
123         payment_hash: PaymentHash,
124         pub(super) incoming_amt_msat: Option<u64>, // Added in 0.0.113
125         pub(super) outgoing_amt_msat: u64,
126         pub(super) outgoing_cltv_value: u32,
127 }
128
129 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
130 pub(super) enum HTLCFailureMsg {
131         Relay(msgs::UpdateFailHTLC),
132         Malformed(msgs::UpdateFailMalformedHTLC),
133 }
134
135 /// Stores whether we can't forward an HTLC or relevant forwarding info
136 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
137 pub(super) enum PendingHTLCStatus {
138         Forward(PendingHTLCInfo),
139         Fail(HTLCFailureMsg),
140 }
141
142 pub(super) struct PendingAddHTLCInfo {
143         pub(super) forward_info: PendingHTLCInfo,
144
145         // These fields are produced in `forward_htlcs()` and consumed in
146         // `process_pending_htlc_forwards()` for constructing the
147         // `HTLCSource::PreviousHopData` for failed and forwarded
148         // HTLCs.
149         //
150         // Note that this may be an outbound SCID alias for the associated channel.
151         prev_short_channel_id: u64,
152         prev_htlc_id: u64,
153         prev_funding_outpoint: OutPoint,
154         prev_user_channel_id: u128,
155 }
156
157 pub(super) enum HTLCForwardInfo {
158         AddHTLC(PendingAddHTLCInfo),
159         FailHTLC {
160                 htlc_id: u64,
161                 err_packet: msgs::OnionErrorPacket,
162         },
163 }
164
165 /// Tracks the inbound corresponding to an outbound HTLC
166 #[derive(Clone, Hash, PartialEq, Eq)]
167 pub(crate) struct HTLCPreviousHopData {
168         // Note that this may be an outbound SCID alias for the associated channel.
169         short_channel_id: u64,
170         htlc_id: u64,
171         incoming_packet_shared_secret: [u8; 32],
172         phantom_shared_secret: Option<[u8; 32]>,
173
174         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
175         // channel with a preimage provided by the forward channel.
176         outpoint: OutPoint,
177 }
178
179 enum OnionPayload {
180         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
181         Invoice {
182                 /// This is only here for backwards-compatibility in serialization, in the future it can be
183                 /// removed, breaking clients running 0.0.106 and earlier.
184                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
185         },
186         /// Contains the payer-provided preimage.
187         Spontaneous(PaymentPreimage),
188 }
189
190 /// HTLCs that are to us and can be failed/claimed by the user
191 struct ClaimableHTLC {
192         prev_hop: HTLCPreviousHopData,
193         cltv_expiry: u32,
194         /// The amount (in msats) of this MPP part
195         value: u64,
196         onion_payload: OnionPayload,
197         timer_ticks: u8,
198         /// The sum total of all MPP parts
199         total_msat: u64,
200 }
201
202 /// A payment identifier used to uniquely identify a payment to LDK.
203 /// (C-not exported) as we just use [u8; 32] directly
204 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
205 pub struct PaymentId(pub [u8; 32]);
206
207 impl Writeable for PaymentId {
208         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
209                 self.0.write(w)
210         }
211 }
212
213 impl Readable for PaymentId {
214         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
215                 let buf: [u8; 32] = Readable::read(r)?;
216                 Ok(PaymentId(buf))
217         }
218 }
219
220 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
221 /// (C-not exported) as we just use [u8; 32] directly
222 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
223 pub struct InterceptId(pub [u8; 32]);
224
225 impl Writeable for InterceptId {
226         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
227                 self.0.write(w)
228         }
229 }
230
231 impl Readable for InterceptId {
232         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
233                 let buf: [u8; 32] = Readable::read(r)?;
234                 Ok(InterceptId(buf))
235         }
236 }
237 /// Tracks the inbound corresponding to an outbound HTLC
238 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
239 #[derive(Clone, PartialEq, Eq)]
240 pub(crate) enum HTLCSource {
241         PreviousHopData(HTLCPreviousHopData),
242         OutboundRoute {
243                 path: Vec<RouteHop>,
244                 session_priv: SecretKey,
245                 /// Technically we can recalculate this from the route, but we cache it here to avoid
246                 /// doing a double-pass on route when we get a failure back
247                 first_hop_htlc_msat: u64,
248                 payment_id: PaymentId,
249                 payment_secret: Option<PaymentSecret>,
250                 payment_params: Option<PaymentParameters>,
251         },
252 }
253 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
254 impl core::hash::Hash for HTLCSource {
255         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
256                 match self {
257                         HTLCSource::PreviousHopData(prev_hop_data) => {
258                                 0u8.hash(hasher);
259                                 prev_hop_data.hash(hasher);
260                         },
261                         HTLCSource::OutboundRoute { path, session_priv, payment_id, payment_secret, first_hop_htlc_msat, payment_params } => {
262                                 1u8.hash(hasher);
263                                 path.hash(hasher);
264                                 session_priv[..].hash(hasher);
265                                 payment_id.hash(hasher);
266                                 payment_secret.hash(hasher);
267                                 first_hop_htlc_msat.hash(hasher);
268                                 payment_params.hash(hasher);
269                         },
270                 }
271         }
272 }
273 #[cfg(not(feature = "grind_signatures"))]
274 #[cfg(test)]
275 impl HTLCSource {
276         pub fn dummy() -> Self {
277                 HTLCSource::OutboundRoute {
278                         path: Vec::new(),
279                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
280                         first_hop_htlc_msat: 0,
281                         payment_id: PaymentId([2; 32]),
282                         payment_secret: None,
283                         payment_params: None,
284                 }
285         }
286 }
287
288 struct ReceiveError {
289         err_code: u16,
290         err_data: Vec<u8>,
291         msg: &'static str,
292 }
293
294 type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash, PublicKey, [u8; 32])>);
295
296 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
297 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
298 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
299 /// channel_state lock. We then return the set of things that need to be done outside the lock in
300 /// this struct and call handle_error!() on it.
301
302 struct MsgHandleErrInternal {
303         err: msgs::LightningError,
304         chan_id: Option<([u8; 32], u128)>, // If Some a channel of ours has been closed
305         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
306 }
307 impl MsgHandleErrInternal {
308         #[inline]
309         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
310                 Self {
311                         err: LightningError {
312                                 err: err.clone(),
313                                 action: msgs::ErrorAction::SendErrorMessage {
314                                         msg: msgs::ErrorMessage {
315                                                 channel_id,
316                                                 data: err
317                                         },
318                                 },
319                         },
320                         chan_id: None,
321                         shutdown_finish: None,
322                 }
323         }
324         #[inline]
325         fn ignore_no_close(err: String) -> Self {
326                 Self {
327                         err: LightningError {
328                                 err,
329                                 action: msgs::ErrorAction::IgnoreError,
330                         },
331                         chan_id: None,
332                         shutdown_finish: None,
333                 }
334         }
335         #[inline]
336         fn from_no_close(err: msgs::LightningError) -> Self {
337                 Self { err, chan_id: None, shutdown_finish: None }
338         }
339         #[inline]
340         fn from_finish_shutdown(err: String, channel_id: [u8; 32], user_channel_id: u128, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
341                 Self {
342                         err: LightningError {
343                                 err: err.clone(),
344                                 action: msgs::ErrorAction::SendErrorMessage {
345                                         msg: msgs::ErrorMessage {
346                                                 channel_id,
347                                                 data: err
348                                         },
349                                 },
350                         },
351                         chan_id: Some((channel_id, user_channel_id)),
352                         shutdown_finish: Some((shutdown_res, channel_update)),
353                 }
354         }
355         #[inline]
356         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
357                 Self {
358                         err: match err {
359                                 ChannelError::Warn(msg) =>  LightningError {
360                                         err: msg.clone(),
361                                         action: msgs::ErrorAction::SendWarningMessage {
362                                                 msg: msgs::WarningMessage {
363                                                         channel_id,
364                                                         data: msg
365                                                 },
366                                                 log_level: Level::Warn,
367                                         },
368                                 },
369                                 ChannelError::Ignore(msg) => LightningError {
370                                         err: msg,
371                                         action: msgs::ErrorAction::IgnoreError,
372                                 },
373                                 ChannelError::Close(msg) => LightningError {
374                                         err: msg.clone(),
375                                         action: msgs::ErrorAction::SendErrorMessage {
376                                                 msg: msgs::ErrorMessage {
377                                                         channel_id,
378                                                         data: msg
379                                                 },
380                                         },
381                                 },
382                         },
383                         chan_id: None,
384                         shutdown_finish: None,
385                 }
386         }
387 }
388
389 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
390 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
391 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
392 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
393 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
394
395 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
396 /// be sent in the order they appear in the return value, however sometimes the order needs to be
397 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
398 /// they were originally sent). In those cases, this enum is also returned.
399 #[derive(Clone, PartialEq)]
400 pub(super) enum RAACommitmentOrder {
401         /// Send the CommitmentUpdate messages first
402         CommitmentFirst,
403         /// Send the RevokeAndACK message first
404         RevokeAndACKFirst,
405 }
406
407 /// Information about a payment which is currently being claimed.
408 struct ClaimingPayment {
409         amount_msat: u64,
410         payment_purpose: events::PaymentPurpose,
411         receiver_node_id: PublicKey,
412 }
413 impl_writeable_tlv_based!(ClaimingPayment, {
414         (0, amount_msat, required),
415         (2, payment_purpose, required),
416         (4, receiver_node_id, required),
417 });
418
419 /// Information about claimable or being-claimed payments
420 struct ClaimablePayments {
421         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
422         /// failed/claimed by the user.
423         ///
424         /// Note that, no consistency guarantees are made about the channels given here actually
425         /// existing anymore by the time you go to read them!
426         ///
427         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
428         /// we don't get a duplicate payment.
429         claimable_htlcs: HashMap<PaymentHash, (events::PaymentPurpose, Vec<ClaimableHTLC>)>,
430
431         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
432         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
433         /// as an [`events::Event::PaymentClaimed`].
434         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
435 }
436
437 // Note this is only exposed in cfg(test):
438 pub(super) struct ChannelHolder<Signer: Sign> {
439         pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
440         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
441         /// for broadcast messages, where ordering isn't as strict).
442         pub(super) pending_msg_events: Vec<MessageSendEvent>,
443 }
444
445 /// Events which we process internally but cannot be procsesed immediately at the generation site
446 /// for some reason. They are handled in timer_tick_occurred, so may be processed with
447 /// quite some time lag.
448 enum BackgroundEvent {
449         /// Handle a ChannelMonitorUpdate that closes a channel, broadcasting its current latest holder
450         /// commitment transaction.
451         ClosingMonitorUpdate((OutPoint, ChannelMonitorUpdate)),
452 }
453
454 pub(crate) enum MonitorUpdateCompletionAction {
455         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
456         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
457         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
458         /// event can be generated.
459         PaymentClaimed { payment_hash: PaymentHash },
460         /// Indicates an [`events::Event`] should be surfaced to the user.
461         EmitEvent { event: events::Event },
462 }
463
464 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
465 /// the latest Init features we heard from the peer.
466 struct PeerState {
467         latest_features: InitFeatures,
468 }
469
470 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
471 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
472 ///
473 /// For users who don't want to bother doing their own payment preimage storage, we also store that
474 /// here.
475 ///
476 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
477 /// and instead encoding it in the payment secret.
478 struct PendingInboundPayment {
479         /// The payment secret that the sender must use for us to accept this payment
480         payment_secret: PaymentSecret,
481         /// Time at which this HTLC expires - blocks with a header time above this value will result in
482         /// this payment being removed.
483         expiry_time: u64,
484         /// Arbitrary identifier the user specifies (or not)
485         user_payment_id: u64,
486         // Other required attributes of the payment, optionally enforced:
487         payment_preimage: Option<PaymentPreimage>,
488         min_value_msat: Option<u64>,
489 }
490
491 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
492 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
493 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
494 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
495 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
496 /// that implements KeysInterface or Router for its keys manager and router, respectively, but this
497 /// type alias chooses the concrete types of KeysManager and DefaultRouter.
498 ///
499 /// (C-not exported) as Arcs don't make sense in bindings
500 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
501         Arc<M>,
502         Arc<T>,
503         Arc<KeysManager>,
504         Arc<F>,
505         Arc<DefaultRouter<
506                 Arc<NetworkGraph<Arc<L>>>,
507                 Arc<L>,
508                 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>
509         >>,
510         Arc<L>
511 >;
512
513 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
514 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
515 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
516 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
517 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
518 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
519 /// that implements KeysInterface or Router for its keys manager and router, respectively, but this
520 /// type alias chooses the concrete types of KeysManager and DefaultRouter.
521 ///
522 /// (C-not exported) as Arcs don't make sense in bindings
523 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> = ChannelManager<&'a M, &'b T, &'c KeysManager, &'d F, &'e DefaultRouter<&'f NetworkGraph<&'g L>, &'g L, &'h Mutex<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>>, &'g L>;
524
525 /// Manager which keeps track of a number of channels and sends messages to the appropriate
526 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
527 ///
528 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
529 /// to individual Channels.
530 ///
531 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
532 /// all peers during write/read (though does not modify this instance, only the instance being
533 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
534 /// called funding_transaction_generated for outbound channels).
535 ///
536 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
537 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
538 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
539 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
540 /// the serialization process). If the deserialized version is out-of-date compared to the
541 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
542 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
543 ///
544 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
545 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
546 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
547 /// block_connected() to step towards your best block) upon deserialization before using the
548 /// object!
549 ///
550 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
551 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
552 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
553 /// offline for a full minute. In order to track this, you must call
554 /// timer_tick_occurred roughly once per minute, though it doesn't have to be perfect.
555 ///
556 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
557 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
558 /// essentially you should default to using a SimpleRefChannelManager, and use a
559 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
560 /// you're using lightning-net-tokio.
561 //
562 // Lock order:
563 // The tree structure below illustrates the lock order requirements for the different locks of the
564 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
565 // and should then be taken in the order of the lowest to the highest level in the tree.
566 // Note that locks on different branches shall not be taken at the same time, as doing so will
567 // create a new lock order for those specific locks in the order they were taken.
568 //
569 // Lock order tree:
570 //
571 // `total_consistency_lock`
572 //  |
573 //  |__`forward_htlcs`
574 //  |   |
575 //  |   |__`pending_intercepted_htlcs`
576 //  |
577 //  |__`pending_inbound_payments`
578 //  |   |
579 //  |   |__`claimable_payments`
580 //  |   |
581 //  |   |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
582 //  |       |
583 //  |       |__`channel_state`
584 //  |           |
585 //  |           |__`id_to_peer`
586 //  |           |
587 //  |           |__`short_to_chan_info`
588 //  |           |
589 //  |           |__`per_peer_state`
590 //  |               |
591 //  |               |__`outbound_scid_aliases`
592 //  |               |
593 //  |               |__`best_block`
594 //  |               |
595 //  |               |__`pending_events`
596 //  |                   |
597 //  |                   |__`pending_background_events`
598 //
599 pub struct ChannelManager<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref>
600 where
601         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
602         T::Target: BroadcasterInterface,
603         K::Target: KeysInterface,
604         F::Target: FeeEstimator,
605         R::Target: Router,
606         L::Target: Logger,
607 {
608         default_configuration: UserConfig,
609         genesis_hash: BlockHash,
610         fee_estimator: LowerBoundedFeeEstimator<F>,
611         chain_monitor: M,
612         tx_broadcaster: T,
613         #[allow(unused)]
614         router: R,
615
616         /// See `ChannelManager` struct-level documentation for lock order requirements.
617         #[cfg(test)]
618         pub(super) best_block: RwLock<BestBlock>,
619         #[cfg(not(test))]
620         best_block: RwLock<BestBlock>,
621         secp_ctx: Secp256k1<secp256k1::All>,
622
623         /// See `ChannelManager` struct-level documentation for lock order requirements.
624         #[cfg(any(test, feature = "_test_utils"))]
625         pub(super) channel_state: Mutex<ChannelHolder<<K::Target as SignerProvider>::Signer>>,
626         #[cfg(not(any(test, feature = "_test_utils")))]
627         channel_state: Mutex<ChannelHolder<<K::Target as SignerProvider>::Signer>>,
628
629         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
630         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
631         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
632         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
633         ///
634         /// See `ChannelManager` struct-level documentation for lock order requirements.
635         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
636
637         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
638         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
639         /// (if the channel has been force-closed), however we track them here to prevent duplicative
640         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
641         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
642         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
643         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
644         /// after reloading from disk while replaying blocks against ChannelMonitors.
645         ///
646         /// See `PendingOutboundPayment` documentation for more info.
647         ///
648         /// See `ChannelManager` struct-level documentation for lock order requirements.
649         pending_outbound_payments: OutboundPayments,
650
651         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
652         ///
653         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
654         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
655         /// and via the classic SCID.
656         ///
657         /// Note that no consistency guarantees are made about the existence of a channel with the
658         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
659         ///
660         /// See `ChannelManager` struct-level documentation for lock order requirements.
661         #[cfg(test)]
662         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
663         #[cfg(not(test))]
664         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
665         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
666         /// until the user tells us what we should do with them.
667         ///
668         /// See `ChannelManager` struct-level documentation for lock order requirements.
669         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
670
671         /// The sets of payments which are claimable or currently being claimed. See
672         /// [`ClaimablePayments`]' individual field docs for more info.
673         ///
674         /// See `ChannelManager` struct-level documentation for lock order requirements.
675         claimable_payments: Mutex<ClaimablePayments>,
676
677         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
678         /// and some closed channels which reached a usable state prior to being closed. This is used
679         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
680         /// active channel list on load.
681         ///
682         /// See `ChannelManager` struct-level documentation for lock order requirements.
683         outbound_scid_aliases: Mutex<HashSet<u64>>,
684
685         /// `channel_id` -> `counterparty_node_id`.
686         ///
687         /// Only `channel_id`s are allowed as keys in this map, and not `temporary_channel_id`s. As
688         /// multiple channels with the same `temporary_channel_id` to different peers can exist,
689         /// allowing `temporary_channel_id`s in this map would cause collisions for such channels.
690         ///
691         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
692         /// the corresponding channel for the event, as we only have access to the `channel_id` during
693         /// the handling of the events.
694         ///
695         /// TODO:
696         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
697         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
698         /// would break backwards compatability.
699         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
700         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
701         /// required to access the channel with the `counterparty_node_id`.
702         ///
703         /// See `ChannelManager` struct-level documentation for lock order requirements.
704         id_to_peer: Mutex<HashMap<[u8; 32], PublicKey>>,
705
706         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
707         ///
708         /// Outbound SCID aliases are added here once the channel is available for normal use, with
709         /// SCIDs being added once the funding transaction is confirmed at the channel's required
710         /// confirmation depth.
711         ///
712         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
713         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
714         /// channel with the `channel_id` in our other maps.
715         ///
716         /// See `ChannelManager` struct-level documentation for lock order requirements.
717         #[cfg(test)]
718         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
719         #[cfg(not(test))]
720         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, [u8; 32])>>,
721
722         our_network_key: SecretKey,
723         our_network_pubkey: PublicKey,
724
725         inbound_payment_key: inbound_payment::ExpandedKey,
726
727         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
728         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
729         /// we encrypt the namespace identifier using these bytes.
730         ///
731         /// [fake scids]: crate::util::scid_utils::fake_scid
732         fake_scid_rand_bytes: [u8; 32],
733
734         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
735         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
736         /// keeping additional state.
737         probing_cookie_secret: [u8; 32],
738
739         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
740         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
741         /// very far in the past, and can only ever be up to two hours in the future.
742         highest_seen_timestamp: AtomicUsize,
743
744         /// The bulk of our storage will eventually be here (channels and message queues and the like).
745         /// If we are connected to a peer we always at least have an entry here, even if no channels
746         /// are currently open with that peer.
747         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
748         /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
749         /// new channel.
750         ///
751         /// See `ChannelManager` struct-level documentation for lock order requirements.
752         per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
753
754         /// See `ChannelManager` struct-level documentation for lock order requirements.
755         pending_events: Mutex<Vec<events::Event>>,
756         /// See `ChannelManager` struct-level documentation for lock order requirements.
757         pending_background_events: Mutex<Vec<BackgroundEvent>>,
758         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
759         /// Essentially just when we're serializing ourselves out.
760         /// Taken first everywhere where we are making changes before any other locks.
761         /// When acquiring this lock in read mode, rather than acquiring it directly, call
762         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
763         /// Notifier the lock contains sends out a notification when the lock is released.
764         total_consistency_lock: RwLock<()>,
765
766         persistence_notifier: Notifier,
767
768         keys_manager: K,
769
770         logger: L,
771 }
772
773 /// Chain-related parameters used to construct a new `ChannelManager`.
774 ///
775 /// Typically, the block-specific parameters are derived from the best block hash for the network,
776 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
777 /// are not needed when deserializing a previously constructed `ChannelManager`.
778 #[derive(Clone, Copy, PartialEq)]
779 pub struct ChainParameters {
780         /// The network for determining the `chain_hash` in Lightning messages.
781         pub network: Network,
782
783         /// The hash and height of the latest block successfully connected.
784         ///
785         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
786         pub best_block: BestBlock,
787 }
788
789 #[derive(Copy, Clone, PartialEq)]
790 enum NotifyOption {
791         DoPersist,
792         SkipPersist,
793 }
794
795 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
796 /// desirable to notify any listeners on `await_persistable_update_timeout`/
797 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
798 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
799 /// sending the aforementioned notification (since the lock being released indicates that the
800 /// updates are ready for persistence).
801 ///
802 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
803 /// notify or not based on whether relevant changes have been made, providing a closure to
804 /// `optionally_notify` which returns a `NotifyOption`.
805 struct PersistenceNotifierGuard<'a, F: Fn() -> NotifyOption> {
806         persistence_notifier: &'a Notifier,
807         should_persist: F,
808         // We hold onto this result so the lock doesn't get released immediately.
809         _read_guard: RwLockReadGuard<'a, ()>,
810 }
811
812 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
813         fn notify_on_drop(lock: &'a RwLock<()>, notifier: &'a Notifier) -> PersistenceNotifierGuard<'a, impl Fn() -> NotifyOption> {
814                 PersistenceNotifierGuard::optionally_notify(lock, notifier, || -> NotifyOption { NotifyOption::DoPersist })
815         }
816
817         fn optionally_notify<F: Fn() -> NotifyOption>(lock: &'a RwLock<()>, notifier: &'a Notifier, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
818                 let read_guard = lock.read().unwrap();
819
820                 PersistenceNotifierGuard {
821                         persistence_notifier: notifier,
822                         should_persist: persist_check,
823                         _read_guard: read_guard,
824                 }
825         }
826 }
827
828 impl<'a, F: Fn() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
829         fn drop(&mut self) {
830                 if (self.should_persist)() == NotifyOption::DoPersist {
831                         self.persistence_notifier.notify();
832                 }
833         }
834 }
835
836 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
837 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
838 ///
839 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
840 ///
841 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
842 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
843 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
844 /// the maximum required amount in lnd as of March 2021.
845 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
846
847 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
848 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
849 ///
850 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
851 ///
852 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
853 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
854 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
855 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
856 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
857 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
858 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
859 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
860 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
861 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
862 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
863 // routing failure for any HTLC sender picking up an LDK node among the first hops.
864 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
865
866 /// Minimum CLTV difference between the current block height and received inbound payments.
867 /// Invoices generated for payment to us must set their `min_final_cltv_expiry` field to at least
868 /// this value.
869 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
870 // any payments to succeed. Further, we don't want payments to fail if a block was found while
871 // a payment was being routed, so we add an extra block to be safe.
872 pub const MIN_FINAL_CLTV_EXPIRY: u32 = HTLC_FAIL_BACK_BUFFER + 3;
873
874 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
875 // ie that if the next-hop peer fails the HTLC within
876 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
877 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
878 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
879 // LATENCY_GRACE_PERIOD_BLOCKS.
880 #[deny(const_err)]
881 #[allow(dead_code)]
882 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;
883
884 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
885 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
886 #[deny(const_err)]
887 #[allow(dead_code)]
888 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
889
890 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
891 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
892
893 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the
894 /// idempotency of payments by [`PaymentId`]. See
895 /// [`OutboundPayments::remove_stale_resolved_payments`].
896 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
897
898 /// Information needed for constructing an invoice route hint for this channel.
899 #[derive(Clone, Debug, PartialEq)]
900 pub struct CounterpartyForwardingInfo {
901         /// Base routing fee in millisatoshis.
902         pub fee_base_msat: u32,
903         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
904         pub fee_proportional_millionths: u32,
905         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
906         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
907         /// `cltv_expiry_delta` for more details.
908         pub cltv_expiry_delta: u16,
909 }
910
911 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
912 /// to better separate parameters.
913 #[derive(Clone, Debug, PartialEq)]
914 pub struct ChannelCounterparty {
915         /// The node_id of our counterparty
916         pub node_id: PublicKey,
917         /// The Features the channel counterparty provided upon last connection.
918         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
919         /// many routing-relevant features are present in the init context.
920         pub features: InitFeatures,
921         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
922         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
923         /// claiming at least this value on chain.
924         ///
925         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
926         ///
927         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
928         pub unspendable_punishment_reserve: u64,
929         /// Information on the fees and requirements that the counterparty requires when forwarding
930         /// payments to us through this channel.
931         pub forwarding_info: Option<CounterpartyForwardingInfo>,
932         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
933         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
934         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
935         pub outbound_htlc_minimum_msat: Option<u64>,
936         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
937         pub outbound_htlc_maximum_msat: Option<u64>,
938 }
939
940 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
941 #[derive(Clone, Debug, PartialEq)]
942 pub struct ChannelDetails {
943         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
944         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
945         /// Note that this means this value is *not* persistent - it can change once during the
946         /// lifetime of the channel.
947         pub channel_id: [u8; 32],
948         /// Parameters which apply to our counterparty. See individual fields for more information.
949         pub counterparty: ChannelCounterparty,
950         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
951         /// our counterparty already.
952         ///
953         /// Note that, if this has been set, `channel_id` will be equivalent to
954         /// `funding_txo.unwrap().to_channel_id()`.
955         pub funding_txo: Option<OutPoint>,
956         /// The features which this channel operates with. See individual features for more info.
957         ///
958         /// `None` until negotiation completes and the channel type is finalized.
959         pub channel_type: Option<ChannelTypeFeatures>,
960         /// The position of the funding transaction in the chain. None if the funding transaction has
961         /// not yet been confirmed and the channel fully opened.
962         ///
963         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
964         /// payments instead of this. See [`get_inbound_payment_scid`].
965         ///
966         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
967         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
968         ///
969         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
970         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
971         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
972         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
973         /// [`confirmations_required`]: Self::confirmations_required
974         pub short_channel_id: Option<u64>,
975         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
976         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
977         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
978         /// `Some(0)`).
979         ///
980         /// This will be `None` as long as the channel is not available for routing outbound payments.
981         ///
982         /// [`short_channel_id`]: Self::short_channel_id
983         /// [`confirmations_required`]: Self::confirmations_required
984         pub outbound_scid_alias: Option<u64>,
985         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
986         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
987         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
988         /// when they see a payment to be routed to us.
989         ///
990         /// Our counterparty may choose to rotate this value at any time, though will always recognize
991         /// previous values for inbound payment forwarding.
992         ///
993         /// [`short_channel_id`]: Self::short_channel_id
994         pub inbound_scid_alias: Option<u64>,
995         /// The value, in satoshis, of this channel as appears in the funding output
996         pub channel_value_satoshis: u64,
997         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
998         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
999         /// this value on chain.
1000         ///
1001         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1002         ///
1003         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1004         ///
1005         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1006         pub unspendable_punishment_reserve: Option<u64>,
1007         /// The `user_channel_id` passed in to create_channel, or a random value if the channel was
1008         /// inbound. This may be zero for inbound channels serialized with LDK versions prior to
1009         /// 0.0.113.
1010         pub user_channel_id: u128,
1011         /// Our total balance.  This is the amount we would get if we close the channel.
1012         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1013         /// amount is not likely to be recoverable on close.
1014         ///
1015         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1016         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1017         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1018         /// This does not consider any on-chain fees.
1019         ///
1020         /// See also [`ChannelDetails::outbound_capacity_msat`]
1021         pub balance_msat: u64,
1022         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1023         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1024         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1025         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1026         ///
1027         /// See also [`ChannelDetails::balance_msat`]
1028         ///
1029         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1030         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1031         /// should be able to spend nearly this amount.
1032         pub outbound_capacity_msat: u64,
1033         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1034         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1035         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1036         /// to use a limit as close as possible to the HTLC limit we can currently send.
1037         ///
1038         /// See also [`ChannelDetails::balance_msat`] and [`ChannelDetails::outbound_capacity_msat`].
1039         pub next_outbound_htlc_limit_msat: u64,
1040         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1041         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1042         /// available for inclusion in new inbound HTLCs).
1043         /// Note that there are some corner cases not fully handled here, so the actual available
1044         /// inbound capacity may be slightly higher than this.
1045         ///
1046         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1047         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1048         /// However, our counterparty should be able to spend nearly this amount.
1049         pub inbound_capacity_msat: u64,
1050         /// The number of required confirmations on the funding transaction before the funding will be
1051         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1052         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1053         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1054         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1055         ///
1056         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1057         ///
1058         /// [`is_outbound`]: ChannelDetails::is_outbound
1059         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1060         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1061         pub confirmations_required: Option<u32>,
1062         /// The current number of confirmations on the funding transaction.
1063         ///
1064         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1065         pub confirmations: Option<u32>,
1066         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1067         /// until we can claim our funds after we force-close the channel. During this time our
1068         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1069         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1070         /// time to claim our non-HTLC-encumbered funds.
1071         ///
1072         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1073         pub force_close_spend_delay: Option<u16>,
1074         /// True if the channel was initiated (and thus funded) by us.
1075         pub is_outbound: bool,
1076         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1077         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1078         /// required confirmation count has been reached (and we were connected to the peer at some
1079         /// point after the funding transaction received enough confirmations). The required
1080         /// confirmation count is provided in [`confirmations_required`].
1081         ///
1082         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1083         pub is_channel_ready: bool,
1084         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1085         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1086         ///
1087         /// This is a strict superset of `is_channel_ready`.
1088         pub is_usable: bool,
1089         /// True if this channel is (or will be) publicly-announced.
1090         pub is_public: bool,
1091         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1092         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1093         pub inbound_htlc_minimum_msat: Option<u64>,
1094         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1095         pub inbound_htlc_maximum_msat: Option<u64>,
1096         /// Set of configurable parameters that affect channel operation.
1097         ///
1098         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1099         pub config: Option<ChannelConfig>,
1100 }
1101
1102 impl ChannelDetails {
1103         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1104         /// This should be used for providing invoice hints or in any other context where our
1105         /// counterparty will forward a payment to us.
1106         ///
1107         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1108         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1109         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1110                 self.inbound_scid_alias.or(self.short_channel_id)
1111         }
1112
1113         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1114         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1115         /// we're sending or forwarding a payment outbound over this channel.
1116         ///
1117         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1118         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1119         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1120                 self.short_channel_id.or(self.outbound_scid_alias)
1121         }
1122 }
1123
1124 /// Route hints used in constructing invoices for [phantom node payents].
1125 ///
1126 /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
1127 #[derive(Clone)]
1128 pub struct PhantomRouteHints {
1129         /// The list of channels to be included in the invoice route hints.
1130         pub channels: Vec<ChannelDetails>,
1131         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1132         /// route hints.
1133         pub phantom_scid: u64,
1134         /// The pubkey of the real backing node that would ultimately receive the payment.
1135         pub real_node_pubkey: PublicKey,
1136 }
1137
1138 macro_rules! handle_error {
1139         ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
1140                 match $internal {
1141                         Ok(msg) => Ok(msg),
1142                         Err(MsgHandleErrInternal { err, chan_id, shutdown_finish }) => {
1143                                 #[cfg(debug_assertions)]
1144                                 {
1145                                         // In testing, ensure there are no deadlocks where the lock is already held upon
1146                                         // entering the macro.
1147                                         assert!($self.channel_state.try_lock().is_ok());
1148                                         assert!($self.pending_events.try_lock().is_ok());
1149                                 }
1150
1151                                 let mut msg_events = Vec::with_capacity(2);
1152
1153                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1154                                         $self.finish_force_close_channel(shutdown_res);
1155                                         if let Some(update) = update_option {
1156                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1157                                                         msg: update
1158                                                 });
1159                                         }
1160                                         if let Some((channel_id, user_channel_id)) = chan_id {
1161                                                 $self.pending_events.lock().unwrap().push(events::Event::ChannelClosed {
1162                                                         channel_id, user_channel_id,
1163                                                         reason: ClosureReason::ProcessingError { err: err.err.clone() }
1164                                                 });
1165                                         }
1166                                 }
1167
1168                                 log_error!($self.logger, "{}", err.err);
1169                                 if let msgs::ErrorAction::IgnoreError = err.action {
1170                                 } else {
1171                                         msg_events.push(events::MessageSendEvent::HandleError {
1172                                                 node_id: $counterparty_node_id,
1173                                                 action: err.action.clone()
1174                                         });
1175                                 }
1176
1177                                 if !msg_events.is_empty() {
1178                                         $self.channel_state.lock().unwrap().pending_msg_events.append(&mut msg_events);
1179                                 }
1180
1181                                 // Return error in case higher-API need one
1182                                 Err(err)
1183                         },
1184                 }
1185         }
1186 }
1187
1188 macro_rules! update_maps_on_chan_removal {
1189         ($self: expr, $channel: expr) => {{
1190                 $self.id_to_peer.lock().unwrap().remove(&$channel.channel_id());
1191                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1192                 if let Some(short_id) = $channel.get_short_channel_id() {
1193                         short_to_chan_info.remove(&short_id);
1194                 } else {
1195                         // If the channel was never confirmed on-chain prior to its closure, remove the
1196                         // outbound SCID alias we used for it from the collision-prevention set. While we
1197                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
1198                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
1199                         // opening a million channels with us which are closed before we ever reach the funding
1200                         // stage.
1201                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel.outbound_scid_alias());
1202                         debug_assert!(alias_removed);
1203                 }
1204                 short_to_chan_info.remove(&$channel.outbound_scid_alias());
1205         }}
1206 }
1207
1208 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
1209 macro_rules! convert_chan_err {
1210         ($self: ident, $err: expr, $channel: expr, $channel_id: expr) => {
1211                 match $err {
1212                         ChannelError::Warn(msg) => {
1213                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), $channel_id.clone()))
1214                         },
1215                         ChannelError::Ignore(msg) => {
1216                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $channel_id.clone()))
1217                         },
1218                         ChannelError::Close(msg) => {
1219                                 log_error!($self.logger, "Closing channel {} due to close-required error: {}", log_bytes!($channel_id[..]), msg);
1220                                 update_maps_on_chan_removal!($self, $channel);
1221                                 let shutdown_res = $channel.force_shutdown(true);
1222                                 (true, MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, $channel.get_user_id(),
1223                                         shutdown_res, $self.get_channel_update_for_broadcast(&$channel).ok()))
1224                         },
1225                 }
1226         }
1227 }
1228
1229 macro_rules! break_chan_entry {
1230         ($self: ident, $res: expr, $entry: expr) => {
1231                 match $res {
1232                         Ok(res) => res,
1233                         Err(e) => {
1234                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1235                                 if drop {
1236                                         $entry.remove_entry();
1237                                 }
1238                                 break Err(res);
1239                         }
1240                 }
1241         }
1242 }
1243
1244 macro_rules! try_chan_entry {
1245         ($self: ident, $res: expr, $entry: expr) => {
1246                 match $res {
1247                         Ok(res) => res,
1248                         Err(e) => {
1249                                 let (drop, res) = convert_chan_err!($self, e, $entry.get_mut(), $entry.key());
1250                                 if drop {
1251                                         $entry.remove_entry();
1252                                 }
1253                                 return Err(res);
1254                         }
1255                 }
1256         }
1257 }
1258
1259 macro_rules! remove_channel {
1260         ($self: expr, $entry: expr) => {
1261                 {
1262                         let channel = $entry.remove_entry().1;
1263                         update_maps_on_chan_removal!($self, channel);
1264                         channel
1265                 }
1266         }
1267 }
1268
1269 macro_rules! handle_monitor_update_res {
1270         ($self: ident, $err: expr, $chan: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $resend_channel_ready: expr, $failed_forwards: expr, $failed_fails: expr, $failed_finalized_fulfills: expr, $chan_id: expr) => {
1271                 match $err {
1272                         ChannelMonitorUpdateStatus::PermanentFailure => {
1273                                 log_error!($self.logger, "Closing channel {} due to monitor update ChannelMonitorUpdateStatus::PermanentFailure", log_bytes!($chan_id[..]));
1274                                 update_maps_on_chan_removal!($self, $chan);
1275                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
1276                                 // chain in a confused state! We need to move them into the ChannelMonitor which
1277                                 // will be responsible for failing backwards once things confirm on-chain.
1278                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
1279                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
1280                                 // us bother trying to claim it just to forward on to another peer. If we're
1281                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
1282                                 // given up the preimage yet, so might as well just wait until the payment is
1283                                 // retried, avoiding the on-chain fees.
1284                                 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), *$chan_id, $chan.get_user_id(),
1285                                                 $chan.force_shutdown(false), $self.get_channel_update_for_broadcast(&$chan).ok() ));
1286                                 (res, true)
1287                         },
1288                         ChannelMonitorUpdateStatus::InProgress => {
1289                                 log_info!($self.logger, "Disabling channel {} due to monitor update in progress. On restore will send {} and process {} forwards, {} fails, and {} fulfill finalizations",
1290                                                 log_bytes!($chan_id[..]),
1291                                                 if $resend_commitment && $resend_raa {
1292                                                                 match $action_type {
1293                                                                         RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
1294                                                                         RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
1295                                                                 }
1296                                                         } else if $resend_commitment { "commitment" }
1297                                                         else if $resend_raa { "RAA" }
1298                                                         else { "nothing" },
1299                                                 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
1300                                                 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len(),
1301                                                 (&$failed_finalized_fulfills as &Vec<HTLCSource>).len());
1302                                 if !$resend_commitment {
1303                                         debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
1304                                 }
1305                                 if !$resend_raa {
1306                                         debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
1307                                 }
1308                                 $chan.monitor_updating_paused($resend_raa, $resend_commitment, $resend_channel_ready, $failed_forwards, $failed_fails, $failed_finalized_fulfills);
1309                                 (Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$chan_id)), false)
1310                         },
1311                         ChannelMonitorUpdateStatus::Completed => {
1312                                 (Ok(()), false)
1313                         },
1314                 }
1315         };
1316         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $resend_channel_ready: expr, $failed_forwards: expr, $failed_fails: expr, $failed_finalized_fulfills: expr) => { {
1317                 let (res, drop) = handle_monitor_update_res!($self, $err, $entry.get_mut(), $action_type, $resend_raa, $resend_commitment, $resend_channel_ready, $failed_forwards, $failed_fails, $failed_finalized_fulfills, $entry.key());
1318                 if drop {
1319                         $entry.remove_entry();
1320                 }
1321                 res
1322         } };
1323         ($self: ident, $err: expr, $entry: expr, $action_type: path, $chan_id: expr, COMMITMENT_UPDATE_ONLY) => { {
1324                 debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst);
1325                 handle_monitor_update_res!($self, $err, $entry, $action_type, false, true, false, Vec::new(), Vec::new(), Vec::new(), $chan_id)
1326         } };
1327         ($self: ident, $err: expr, $entry: expr, $action_type: path, $chan_id: expr, NO_UPDATE) => {
1328                 handle_monitor_update_res!($self, $err, $entry, $action_type, false, false, false, Vec::new(), Vec::new(), Vec::new(), $chan_id)
1329         };
1330         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_channel_ready: expr, OPTIONALLY_RESEND_FUNDING_LOCKED) => {
1331                 handle_monitor_update_res!($self, $err, $entry, $action_type, false, false, $resend_channel_ready, Vec::new(), Vec::new(), Vec::new())
1332         };
1333         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
1334                 handle_monitor_update_res!($self, $err, $entry, $action_type, $resend_raa, $resend_commitment, false, Vec::new(), Vec::new(), Vec::new())
1335         };
1336         ($self: ident, $err: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
1337                 handle_monitor_update_res!($self, $err, $entry, $action_type, $resend_raa, $resend_commitment, false, $failed_forwards, $failed_fails, Vec::new())
1338         };
1339 }
1340
1341 macro_rules! send_channel_ready {
1342         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
1343                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
1344                         node_id: $channel.get_counterparty_node_id(),
1345                         msg: $channel_ready_msg,
1346                 });
1347                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
1348                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
1349                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
1350                 let outbound_alias_insert = short_to_chan_info.insert($channel.outbound_scid_alias(), ($channel.get_counterparty_node_id(), $channel.channel_id()));
1351                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.get_counterparty_node_id(), $channel.channel_id()),
1352                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1353                 if let Some(real_scid) = $channel.get_short_channel_id() {
1354                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.get_counterparty_node_id(), $channel.channel_id()));
1355                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.get_counterparty_node_id(), $channel.channel_id()),
1356                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
1357                 }
1358         }}
1359 }
1360
1361 macro_rules! emit_channel_ready_event {
1362         ($self: expr, $channel: expr) => {
1363                 if $channel.should_emit_channel_ready_event() {
1364                         {
1365                                 let mut pending_events = $self.pending_events.lock().unwrap();
1366                                 pending_events.push(events::Event::ChannelReady {
1367                                         channel_id: $channel.channel_id(),
1368                                         user_channel_id: $channel.get_user_id(),
1369                                         counterparty_node_id: $channel.get_counterparty_node_id(),
1370                                         channel_type: $channel.get_channel_type().clone(),
1371                                 });
1372                         }
1373                         $channel.set_channel_ready_event_emitted();
1374                 }
1375         }
1376 }
1377
1378 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref> ChannelManager<M, T, K, F, R, L>
1379 where
1380         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
1381         T::Target: BroadcasterInterface,
1382         K::Target: KeysInterface,
1383         F::Target: FeeEstimator,
1384         R::Target: Router,
1385         L::Target: Logger,
1386 {
1387         /// Constructs a new ChannelManager to hold several channels and route between them.
1388         ///
1389         /// This is the main "logic hub" for all channel-related actions, and implements
1390         /// ChannelMessageHandler.
1391         ///
1392         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
1393         ///
1394         /// Users need to notify the new ChannelManager when a new block is connected or
1395         /// disconnected using its `block_connected` and `block_disconnected` methods, starting
1396         /// from after `params.latest_hash`.
1397         pub fn new(fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, keys_manager: K, config: UserConfig, params: ChainParameters) -> Self {
1398                 let mut secp_ctx = Secp256k1::new();
1399                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
1400                 let inbound_pmt_key_material = keys_manager.get_inbound_payment_key_material();
1401                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
1402                 ChannelManager {
1403                         default_configuration: config.clone(),
1404                         genesis_hash: genesis_block(params.network).header.block_hash(),
1405                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
1406                         chain_monitor,
1407                         tx_broadcaster,
1408                         router,
1409
1410                         best_block: RwLock::new(params.best_block),
1411
1412                         channel_state: Mutex::new(ChannelHolder{
1413                                 by_id: HashMap::new(),
1414                                 pending_msg_events: Vec::new(),
1415                         }),
1416                         outbound_scid_aliases: Mutex::new(HashSet::new()),
1417                         pending_inbound_payments: Mutex::new(HashMap::new()),
1418                         pending_outbound_payments: OutboundPayments::new(),
1419                         forward_htlcs: Mutex::new(HashMap::new()),
1420                         claimable_payments: Mutex::new(ClaimablePayments { claimable_htlcs: HashMap::new(), pending_claiming_payments: HashMap::new() }),
1421                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
1422                         id_to_peer: Mutex::new(HashMap::new()),
1423                         short_to_chan_info: FairRwLock::new(HashMap::new()),
1424
1425                         our_network_key: keys_manager.get_node_secret(Recipient::Node).unwrap(),
1426                         our_network_pubkey: PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret(Recipient::Node).unwrap()),
1427                         secp_ctx,
1428
1429                         inbound_payment_key: expanded_inbound_key,
1430                         fake_scid_rand_bytes: keys_manager.get_secure_random_bytes(),
1431
1432                         probing_cookie_secret: keys_manager.get_secure_random_bytes(),
1433
1434                         highest_seen_timestamp: AtomicUsize::new(0),
1435
1436                         per_peer_state: RwLock::new(HashMap::new()),
1437
1438                         pending_events: Mutex::new(Vec::new()),
1439                         pending_background_events: Mutex::new(Vec::new()),
1440                         total_consistency_lock: RwLock::new(()),
1441                         persistence_notifier: Notifier::new(),
1442
1443                         keys_manager,
1444
1445                         logger,
1446                 }
1447         }
1448
1449         /// Gets the current configuration applied to all new channels.
1450         pub fn get_current_default_configuration(&self) -> &UserConfig {
1451                 &self.default_configuration
1452         }
1453
1454         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
1455                 let height = self.best_block.read().unwrap().height();
1456                 let mut outbound_scid_alias = 0;
1457                 let mut i = 0;
1458                 loop {
1459                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
1460                                 outbound_scid_alias += 1;
1461                         } else {
1462                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.keys_manager);
1463                         }
1464                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
1465                                 break;
1466                         }
1467                         i += 1;
1468                         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"); }
1469                 }
1470                 outbound_scid_alias
1471         }
1472
1473         /// Creates a new outbound channel to the given remote node and with the given value.
1474         ///
1475         /// `user_channel_id` will be provided back as in
1476         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
1477         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
1478         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
1479         /// is simply copied to events and otherwise ignored.
1480         ///
1481         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
1482         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
1483         ///
1484         /// Note that we do not check if you are currently connected to the given peer. If no
1485         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
1486         /// the channel eventually being silently forgotten (dropped on reload).
1487         ///
1488         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
1489         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
1490         /// [`ChannelDetails::channel_id`] until after
1491         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
1492         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
1493         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
1494         ///
1495         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
1496         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
1497         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
1498         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> {
1499                 if channel_value_satoshis < 1000 {
1500                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
1501                 }
1502
1503                 let channel = {
1504                         let per_peer_state = self.per_peer_state.read().unwrap();
1505                         match per_peer_state.get(&their_network_key) {
1506                                 Some(peer_state) => {
1507                                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
1508                                         let peer_state = peer_state.lock().unwrap();
1509                                         let their_features = &peer_state.latest_features;
1510                                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
1511                                         match Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key,
1512                                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
1513                                                 self.best_block.read().unwrap().height(), outbound_scid_alias)
1514                                         {
1515                                                 Ok(res) => res,
1516                                                 Err(e) => {
1517                                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
1518                                                         return Err(e);
1519                                                 },
1520                                         }
1521                                 },
1522                                 None => return Err(APIError::ChannelUnavailable { err: format!("Not connected to node: {}", their_network_key) }),
1523                         }
1524                 };
1525                 let res = channel.get_open_channel(self.genesis_hash.clone());
1526
1527                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1528                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
1529                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
1530
1531                 let temporary_channel_id = channel.channel_id();
1532                 let mut channel_state = self.channel_state.lock().unwrap();
1533                 match channel_state.by_id.entry(temporary_channel_id) {
1534                         hash_map::Entry::Occupied(_) => {
1535                                 if cfg!(fuzzing) {
1536                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
1537                                 } else {
1538                                         panic!("RNG is bad???");
1539                                 }
1540                         },
1541                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
1542                 }
1543                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
1544                         node_id: their_network_key,
1545                         msg: res,
1546                 });
1547                 Ok(temporary_channel_id)
1548         }
1549
1550         fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<<K::Target as SignerProvider>::Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
1551                 let mut res = Vec::new();
1552                 {
1553                         let channel_state = self.channel_state.lock().unwrap();
1554                         let best_block_height = self.best_block.read().unwrap().height();
1555                         res.reserve(channel_state.by_id.len());
1556                         for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
1557                                 let balance = channel.get_available_balances();
1558                                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1559                                         channel.get_holder_counterparty_selected_channel_reserve_satoshis();
1560                                 res.push(ChannelDetails {
1561                                         channel_id: (*channel_id).clone(),
1562                                         counterparty: ChannelCounterparty {
1563                                                 node_id: channel.get_counterparty_node_id(),
1564                                                 features: InitFeatures::empty(),
1565                                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1566                                                 forwarding_info: channel.counterparty_forwarding_info(),
1567                                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1568                                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1569                                                 // message (as they are always the first message from the counterparty).
1570                                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1571                                                 // default `0` value set by `Channel::new_outbound`.
1572                                                 outbound_htlc_minimum_msat: if channel.have_received_message() {
1573                                                         Some(channel.get_counterparty_htlc_minimum_msat()) } else { None },
1574                                                 outbound_htlc_maximum_msat: channel.get_counterparty_htlc_maximum_msat(),
1575                                         },
1576                                         funding_txo: channel.get_funding_txo(),
1577                                         // Note that accept_channel (or open_channel) is always the first message, so
1578                                         // `have_received_message` indicates that type negotiation has completed.
1579                                         channel_type: if channel.have_received_message() { Some(channel.get_channel_type().clone()) } else { None },
1580                                         short_channel_id: channel.get_short_channel_id(),
1581                                         outbound_scid_alias: if channel.is_usable() { Some(channel.outbound_scid_alias()) } else { None },
1582                                         inbound_scid_alias: channel.latest_inbound_scid_alias(),
1583                                         channel_value_satoshis: channel.get_value_satoshis(),
1584                                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1585                                         balance_msat: balance.balance_msat,
1586                                         inbound_capacity_msat: balance.inbound_capacity_msat,
1587                                         outbound_capacity_msat: balance.outbound_capacity_msat,
1588                                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1589                                         user_channel_id: channel.get_user_id(),
1590                                         confirmations_required: channel.minimum_depth(),
1591                                         confirmations: Some(channel.get_funding_tx_confirmations(best_block_height)),
1592                                         force_close_spend_delay: channel.get_counterparty_selected_contest_delay(),
1593                                         is_outbound: channel.is_outbound(),
1594                                         is_channel_ready: channel.is_usable(),
1595                                         is_usable: channel.is_live(),
1596                                         is_public: channel.should_announce(),
1597                                         inbound_htlc_minimum_msat: Some(channel.get_holder_htlc_minimum_msat()),
1598                                         inbound_htlc_maximum_msat: channel.get_holder_htlc_maximum_msat(),
1599                                         config: Some(channel.config()),
1600                                 });
1601                         }
1602                 }
1603                 let per_peer_state = self.per_peer_state.read().unwrap();
1604                 for chan in res.iter_mut() {
1605                         if let Some(peer_state) = per_peer_state.get(&chan.counterparty.node_id) {
1606                                 chan.counterparty.features = peer_state.lock().unwrap().latest_features.clone();
1607                         }
1608                 }
1609                 res
1610         }
1611
1612         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
1613         /// more information.
1614         pub fn list_channels(&self) -> Vec<ChannelDetails> {
1615                 self.list_channels_with_filter(|_| true)
1616         }
1617
1618         /// Gets the list of usable channels, in random order. Useful as an argument to [`find_route`]
1619         /// to ensure non-announced channels are used.
1620         ///
1621         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
1622         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
1623         /// are.
1624         ///
1625         /// [`find_route`]: crate::routing::router::find_route
1626         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
1627                 // Note we use is_live here instead of usable which leads to somewhat confused
1628                 // internal/external nomenclature, but that's ok cause that's probably what the user
1629                 // really wanted anyway.
1630                 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
1631         }
1632
1633         /// Helper function that issues the channel close events
1634         fn issue_channel_close_events(&self, channel: &Channel<<K::Target as SignerProvider>::Signer>, closure_reason: ClosureReason) {
1635                 let mut pending_events_lock = self.pending_events.lock().unwrap();
1636                 match channel.unbroadcasted_funding() {
1637                         Some(transaction) => {
1638                                 pending_events_lock.push(events::Event::DiscardFunding { channel_id: channel.channel_id(), transaction })
1639                         },
1640                         None => {},
1641                 }
1642                 pending_events_lock.push(events::Event::ChannelClosed {
1643                         channel_id: channel.channel_id(),
1644                         user_channel_id: channel.get_user_id(),
1645                         reason: closure_reason
1646                 });
1647         }
1648
1649         fn close_channel_internal(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>) -> Result<(), APIError> {
1650                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1651
1652                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)>;
1653                 let result: Result<(), _> = loop {
1654                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1655                         let channel_state = &mut *channel_state_lock;
1656                         match channel_state.by_id.entry(channel_id.clone()) {
1657                                 hash_map::Entry::Occupied(mut chan_entry) => {
1658                                         if *counterparty_node_id != chan_entry.get().get_counterparty_node_id(){
1659                                                 return Err(APIError::APIMisuseError { err: "The passed counterparty_node_id doesn't match the channel's counterparty node_id".to_owned() });
1660                                         }
1661                                         let (shutdown_msg, monitor_update, htlcs) = {
1662                                                 let per_peer_state = self.per_peer_state.read().unwrap();
1663                                                 match per_peer_state.get(&counterparty_node_id) {
1664                                                         Some(peer_state) => {
1665                                                                 let peer_state = peer_state.lock().unwrap();
1666                                                                 let their_features = &peer_state.latest_features;
1667                                                                 chan_entry.get_mut().get_shutdown(&self.keys_manager, their_features, target_feerate_sats_per_1000_weight)?
1668                                                         },
1669                                                         None => return Err(APIError::ChannelUnavailable { err: format!("Not connected to node: {}", counterparty_node_id) }),
1670                                                 }
1671                                         };
1672                                         failed_htlcs = htlcs;
1673
1674                                         // Update the monitor with the shutdown script if necessary.
1675                                         if let Some(monitor_update) = monitor_update {
1676                                                 let update_res = self.chain_monitor.update_channel(chan_entry.get().get_funding_txo().unwrap(), monitor_update);
1677                                                 let (result, is_permanent) =
1678                                                         handle_monitor_update_res!(self, update_res, chan_entry.get_mut(), RAACommitmentOrder::CommitmentFirst, chan_entry.key(), NO_UPDATE);
1679                                                 if is_permanent {
1680                                                         remove_channel!(self, chan_entry);
1681                                                         break result;
1682                                                 }
1683                                         }
1684
1685                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1686                                                 node_id: *counterparty_node_id,
1687                                                 msg: shutdown_msg
1688                                         });
1689
1690                                         if chan_entry.get().is_shutdown() {
1691                                                 let channel = remove_channel!(self, chan_entry);
1692                                                 if let Ok(channel_update) = self.get_channel_update_for_broadcast(&channel) {
1693                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1694                                                                 msg: channel_update
1695                                                         });
1696                                                 }
1697                                                 self.issue_channel_close_events(&channel, ClosureReason::HolderForceClosed);
1698                                         }
1699                                         break Ok(());
1700                                 },
1701                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()})
1702                         }
1703                 };
1704
1705                 for htlc_source in failed_htlcs.drain(..) {
1706                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
1707                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
1708                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
1709                 }
1710
1711                 let _ = handle_error!(self, result, *counterparty_node_id);
1712                 Ok(())
1713         }
1714
1715         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1716         /// will be accepted on the given channel, and after additional timeout/the closing of all
1717         /// pending HTLCs, the channel will be closed on chain.
1718         ///
1719         ///  * If we are the channel initiator, we will pay between our [`Background`] and
1720         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
1721         ///    estimate.
1722         ///  * If our counterparty is the channel initiator, we will require a channel closing
1723         ///    transaction feerate of at least our [`Background`] feerate or the feerate which
1724         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
1725         ///    counterparty to pay as much fee as they'd like, however.
1726         ///
1727         /// May generate a SendShutdown message event on success, which should be relayed.
1728         ///
1729         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
1730         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
1731         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
1732         pub fn close_channel(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey) -> Result<(), APIError> {
1733                 self.close_channel_internal(channel_id, counterparty_node_id, None)
1734         }
1735
1736         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
1737         /// will be accepted on the given channel, and after additional timeout/the closing of all
1738         /// pending HTLCs, the channel will be closed on chain.
1739         ///
1740         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
1741         /// the channel being closed or not:
1742         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
1743         ///    transaction. The upper-bound is set by
1744         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
1745         ///    estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
1746         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
1747         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
1748         ///    will appear on a force-closure transaction, whichever is lower).
1749         ///
1750         /// May generate a SendShutdown message event on success, which should be relayed.
1751         ///
1752         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
1753         /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
1754         /// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
1755         pub fn close_channel_with_target_feerate(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: u32) -> Result<(), APIError> {
1756                 self.close_channel_internal(channel_id, counterparty_node_id, Some(target_feerate_sats_per_1000_weight))
1757         }
1758
1759         #[inline]
1760         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
1761                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
1762                 log_debug!(self.logger, "Finishing force-closure of channel with {} HTLCs to fail", failed_htlcs.len());
1763                 for htlc_source in failed_htlcs.drain(..) {
1764                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
1765                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
1766                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
1767                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
1768                 }
1769                 if let Some((funding_txo, monitor_update)) = monitor_update_option {
1770                         // There isn't anything we can do if we get an update failure - we're already
1771                         // force-closing. The monitor update on the required in-memory copy should broadcast
1772                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
1773                         // ignore the result here.
1774                         let _ = self.chain_monitor.update_channel(funding_txo, monitor_update);
1775                 }
1776         }
1777
1778         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
1779         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
1780         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
1781         -> Result<PublicKey, APIError> {
1782                 let mut chan = {
1783                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1784                         let channel_state = &mut *channel_state_lock;
1785                         if let hash_map::Entry::Occupied(chan) = channel_state.by_id.entry(channel_id.clone()) {
1786                                 if chan.get().get_counterparty_node_id() != *peer_node_id {
1787                                         return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1788                                 }
1789                                 if let Some(peer_msg) = peer_msg {
1790                                         self.issue_channel_close_events(chan.get(),ClosureReason::CounterpartyForceClosed { peer_msg: peer_msg.to_string() });
1791                                 } else {
1792                                         self.issue_channel_close_events(chan.get(),ClosureReason::HolderForceClosed);
1793                                 }
1794                                 remove_channel!(self, chan)
1795                         } else {
1796                                 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1797                         }
1798                 };
1799                 log_error!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1800                 self.finish_force_close_channel(chan.force_shutdown(broadcast));
1801                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
1802                         let mut channel_state = self.channel_state.lock().unwrap();
1803                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1804                                 msg: update
1805                         });
1806                 }
1807
1808                 Ok(chan.get_counterparty_node_id())
1809         }
1810
1811         fn force_close_sending_error(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
1812                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
1813                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
1814                         Ok(counterparty_node_id) => {
1815                                 self.channel_state.lock().unwrap().pending_msg_events.push(
1816                                         events::MessageSendEvent::HandleError {
1817                                                 node_id: counterparty_node_id,
1818                                                 action: msgs::ErrorAction::SendErrorMessage {
1819                                                         msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
1820                                                 },
1821                                         }
1822                                 );
1823                                 Ok(())
1824                         },
1825                         Err(e) => Err(e)
1826                 }
1827         }
1828
1829         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
1830         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
1831         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
1832         /// channel.
1833         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
1834         -> Result<(), APIError> {
1835                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
1836         }
1837
1838         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
1839         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
1840         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
1841         ///
1842         /// You can always get the latest local transaction(s) to broadcast from
1843         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
1844         pub fn force_close_without_broadcasting_txn(&self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey)
1845         -> Result<(), APIError> {
1846                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
1847         }
1848
1849         /// Force close all channels, immediately broadcasting the latest local commitment transaction
1850         /// for each to the chain and rejecting new HTLCs on each.
1851         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
1852                 for chan in self.list_channels() {
1853                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
1854                 }
1855         }
1856
1857         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
1858         /// local transaction(s).
1859         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
1860                 for chan in self.list_channels() {
1861                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
1862                 }
1863         }
1864
1865         fn construct_recv_pending_htlc_info(&self, hop_data: msgs::OnionHopData, shared_secret: [u8; 32],
1866                 payment_hash: PaymentHash, amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>) -> Result<PendingHTLCInfo, ReceiveError>
1867         {
1868                 // final_incorrect_cltv_expiry
1869                 if hop_data.outgoing_cltv_value != cltv_expiry {
1870                         return Err(ReceiveError {
1871                                 msg: "Upstream node set CLTV to the wrong value",
1872                                 err_code: 18,
1873                                 err_data: cltv_expiry.to_be_bytes().to_vec()
1874                         })
1875                 }
1876                 // final_expiry_too_soon
1877                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
1878                 // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
1879                 // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
1880                 // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
1881                 // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
1882                 let current_height: u32 = self.best_block.read().unwrap().height();
1883                 if (hop_data.outgoing_cltv_value as u64) <= current_height as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1884                         let mut err_data = Vec::with_capacity(12);
1885                         err_data.extend_from_slice(&amt_msat.to_be_bytes());
1886                         err_data.extend_from_slice(&current_height.to_be_bytes());
1887                         return Err(ReceiveError {
1888                                 err_code: 0x4000 | 15, err_data,
1889                                 msg: "The final CLTV expiry is too soon to handle",
1890                         });
1891                 }
1892                 if hop_data.amt_to_forward > amt_msat {
1893                         return Err(ReceiveError {
1894                                 err_code: 19,
1895                                 err_data: amt_msat.to_be_bytes().to_vec(),
1896                                 msg: "Upstream node sent less than we were supposed to receive in payment",
1897                         });
1898                 }
1899
1900                 let routing = match hop_data.format {
1901                         msgs::OnionHopDataFormat::NonFinalNode { .. } => {
1902                                 return Err(ReceiveError {
1903                                         err_code: 0x4000|22,
1904                                         err_data: Vec::new(),
1905                                         msg: "Got non final data with an HMAC of 0",
1906                                 });
1907                         },
1908                         msgs::OnionHopDataFormat::FinalNode { payment_data, keysend_preimage } => {
1909                                 if payment_data.is_some() && keysend_preimage.is_some() {
1910                                         return Err(ReceiveError {
1911                                                 err_code: 0x4000|22,
1912                                                 err_data: Vec::new(),
1913                                                 msg: "We don't support MPP keysend payments",
1914                                         });
1915                                 } else if let Some(data) = payment_data {
1916                                         PendingHTLCRouting::Receive {
1917                                                 payment_data: data,
1918                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
1919                                                 phantom_shared_secret,
1920                                         }
1921                                 } else if let Some(payment_preimage) = keysend_preimage {
1922                                         // We need to check that the sender knows the keysend preimage before processing this
1923                                         // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
1924                                         // could discover the final destination of X, by probing the adjacent nodes on the route
1925                                         // with a keysend payment of identical payment hash to X and observing the processing
1926                                         // time discrepancies due to a hash collision with X.
1927                                         let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1928                                         if hashed_preimage != payment_hash {
1929                                                 return Err(ReceiveError {
1930                                                         err_code: 0x4000|22,
1931                                                         err_data: Vec::new(),
1932                                                         msg: "Payment preimage didn't match payment hash",
1933                                                 });
1934                                         }
1935
1936                                         PendingHTLCRouting::ReceiveKeysend {
1937                                                 payment_preimage,
1938                                                 incoming_cltv_expiry: hop_data.outgoing_cltv_value,
1939                                         }
1940                                 } else {
1941                                         return Err(ReceiveError {
1942                                                 err_code: 0x4000|0x2000|3,
1943                                                 err_data: Vec::new(),
1944                                                 msg: "We require payment_secrets",
1945                                         });
1946                                 }
1947                         },
1948                 };
1949                 Ok(PendingHTLCInfo {
1950                         routing,
1951                         payment_hash,
1952                         incoming_shared_secret: shared_secret,
1953                         incoming_amt_msat: Some(amt_msat),
1954                         outgoing_amt_msat: amt_msat,
1955                         outgoing_cltv_value: hop_data.outgoing_cltv_value,
1956                 })
1957         }
1958
1959         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> PendingHTLCStatus {
1960                 macro_rules! return_malformed_err {
1961                         ($msg: expr, $err_code: expr) => {
1962                                 {
1963                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1964                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
1965                                                 channel_id: msg.channel_id,
1966                                                 htlc_id: msg.htlc_id,
1967                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
1968                                                 failure_code: $err_code,
1969                                         }));
1970                                 }
1971                         }
1972                 }
1973
1974                 if let Err(_) = msg.onion_routing_packet.public_key {
1975                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
1976                 }
1977
1978                 let shared_secret = SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key).secret_bytes();
1979
1980                 if msg.onion_routing_packet.version != 0 {
1981                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1982                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1983                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
1984                         //receiving node would have to brute force to figure out which version was put in the
1985                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1986                         //node knows the HMAC matched, so they already know what is there...
1987                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1988                 }
1989                 macro_rules! return_err {
1990                         ($msg: expr, $err_code: expr, $data: expr) => {
1991                                 {
1992                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1993                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1994                                                 channel_id: msg.channel_id,
1995                                                 htlc_id: msg.htlc_id,
1996                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
1997                                                         .get_encrypted_failure_packet(&shared_secret, &None),
1998                                         }));
1999                                 }
2000                         }
2001                 }
2002
2003                 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) {
2004                         Ok(res) => res,
2005                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2006                                 return_malformed_err!(err_msg, err_code);
2007                         },
2008                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2009                                 return_err!(err_msg, err_code, &[0; 0]);
2010                         },
2011                 };
2012
2013                 let pending_forward_info = match next_hop {
2014                         onion_utils::Hop::Receive(next_hop_data) => {
2015                                 // OUR PAYMENT!
2016                                 match self.construct_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash, msg.amount_msat, msg.cltv_expiry, None) {
2017                                         Ok(info) => {
2018                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
2019                                                 // message, however that would leak that we are the recipient of this payment, so
2020                                                 // instead we stay symmetric with the forwarding case, only responding (after a
2021                                                 // delay) once they've send us a commitment_signed!
2022                                                 PendingHTLCStatus::Forward(info)
2023                                         },
2024                                         Err(ReceiveError { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
2025                                 }
2026                         },
2027                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
2028                                 let new_pubkey = msg.onion_routing_packet.public_key.unwrap();
2029                                 let outgoing_packet = msgs::OnionPacket {
2030                                         version: 0,
2031                                         public_key: onion_utils::next_hop_packet_pubkey(&self.secp_ctx, new_pubkey, &shared_secret),
2032                                         hop_data: new_packet_bytes,
2033                                         hmac: next_hop_hmac.clone(),
2034                                 };
2035
2036                                 let short_channel_id = match next_hop_data.format {
2037                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
2038                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
2039                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
2040                                         },
2041                                 };
2042
2043                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
2044                                         routing: PendingHTLCRouting::Forward {
2045                                                 onion_packet: outgoing_packet,
2046                                                 short_channel_id,
2047                                         },
2048                                         payment_hash: msg.payment_hash.clone(),
2049                                         incoming_shared_secret: shared_secret,
2050                                         incoming_amt_msat: Some(msg.amount_msat),
2051                                         outgoing_amt_msat: next_hop_data.amt_to_forward,
2052                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
2053                                 })
2054                         }
2055                 };
2056
2057                 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref outgoing_amt_msat, ref outgoing_cltv_value, .. }) = &pending_forward_info {
2058                         // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
2059                         // with a short_channel_id of 0. This is important as various things later assume
2060                         // short_channel_id is non-0 in any ::Forward.
2061                         if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
2062                                 if let Some((err, mut code, chan_update)) = loop {
2063                                         let id_option = self.short_to_chan_info.read().unwrap().get(&short_channel_id).cloned();
2064                                         let mut channel_state = self.channel_state.lock().unwrap();
2065                                         let forwarding_id_opt = match id_option {
2066                                                 None => { // unknown_next_peer
2067                                                         // Note that this is likely a timing oracle for detecting whether an scid is a
2068                                                         // phantom or an intercept.
2069                                                         if (self.default_configuration.accept_intercept_htlcs &&
2070                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, *short_channel_id, &self.genesis_hash)) ||
2071                                                            fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, *short_channel_id, &self.genesis_hash)
2072                                                         {
2073                                                                 None
2074                                                         } else {
2075                                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2076                                                         }
2077                                                 },
2078                                                 Some((_cp_id, chan_id)) => Some(chan_id.clone()),
2079                                         };
2080                                         let chan_update_opt = if let Some(forwarding_id) = forwarding_id_opt {
2081                                                 let chan = match channel_state.by_id.get_mut(&forwarding_id) {
2082                                                         None => {
2083                                                                 // Channel was removed. The short_to_chan_info and by_id maps have
2084                                                                 // no consistency guarantees.
2085                                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
2086                                                         },
2087                                                         Some(chan) => chan
2088                                                 };
2089                                                 if !chan.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
2090                                                         // Note that the behavior here should be identical to the above block - we
2091                                                         // should NOT reveal the existence or non-existence of a private channel if
2092                                                         // we don't allow forwards outbound over them.
2093                                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
2094                                                 }
2095                                                 if chan.get_channel_type().supports_scid_privacy() && *short_channel_id != chan.outbound_scid_alias() {
2096                                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
2097                                                         // "refuse to forward unless the SCID alias was used", so we pretend
2098                                                         // we don't have the channel here.
2099                                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
2100                                                 }
2101                                                 let chan_update_opt = self.get_channel_update_for_onion(*short_channel_id, chan).ok();
2102
2103                                                 // Note that we could technically not return an error yet here and just hope
2104                                                 // that the connection is reestablished or monitor updated by the time we get
2105                                                 // around to doing the actual forward, but better to fail early if we can and
2106                                                 // hopefully an attacker trying to path-trace payments cannot make this occur
2107                                                 // on a small/per-node/per-channel scale.
2108                                                 if !chan.is_live() { // channel_disabled
2109                                                         break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, chan_update_opt));
2110                                                 }
2111                                                 if *outgoing_amt_msat < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
2112                                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
2113                                                 }
2114                                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, *outgoing_amt_msat, *outgoing_cltv_value) {
2115                                                         break Some((err, code, chan_update_opt));
2116                                                 }
2117                                                 chan_update_opt
2118                                         } else {
2119                                                 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
2120                                                         // We really should set `incorrect_cltv_expiry` here but as we're not
2121                                                         // forwarding over a real channel we can't generate a channel_update
2122                                                         // for it. Instead we just return a generic temporary_node_failure.
2123                                                         break Some((
2124                                                                 "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
2125                                                                 0x2000 | 2, None,
2126                                                         ));
2127                                                 }
2128                                                 None
2129                                         };
2130
2131                                         let cur_height = self.best_block.read().unwrap().height() + 1;
2132                                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
2133                                         // but we want to be robust wrt to counterparty packet sanitization (see
2134                                         // HTLC_FAIL_BACK_BUFFER rationale).
2135                                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
2136                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, chan_update_opt));
2137                                         }
2138                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
2139                                                 break Some(("CLTV expiry is too far in the future", 21, None));
2140                                         }
2141                                         // If the HTLC expires ~now, don't bother trying to forward it to our
2142                                         // counterparty. They should fail it anyway, but we don't want to bother with
2143                                         // the round-trips or risk them deciding they definitely want the HTLC and
2144                                         // force-closing to ensure they get it if we're offline.
2145                                         // We previously had a much more aggressive check here which tried to ensure
2146                                         // our counterparty receives an HTLC which has *our* risk threshold met on it,
2147                                         // but there is no need to do that, and since we're a bit conservative with our
2148                                         // risk threshold it just results in failing to forward payments.
2149                                         if (*outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
2150                                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, chan_update_opt));
2151                                         }
2152
2153                                         break None;
2154                                 }
2155                                 {
2156                                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
2157                                         if let Some(chan_update) = chan_update {
2158                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
2159                                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
2160                                                 }
2161                                                 else if code == 0x1000 | 13 {
2162                                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
2163                                                 }
2164                                                 else if code == 0x1000 | 20 {
2165                                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
2166                                                         0u16.write(&mut res).expect("Writes cannot fail");
2167                                                 }
2168                                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
2169                                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
2170                                                 chan_update.write(&mut res).expect("Writes cannot fail");
2171                                         } else if code & 0x1000 == 0x1000 {
2172                                                 // If we're trying to return an error that requires a `channel_update` but
2173                                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
2174                                                 // generate an update), just use the generic "temporary_node_failure"
2175                                                 // instead.
2176                                                 code = 0x2000 | 2;
2177                                         }
2178                                         return_err!(err, code, &res.0[..]);
2179                                 }
2180                         }
2181                 }
2182
2183                 pending_forward_info
2184         }
2185
2186         /// Gets the current channel_update for the given channel. This first checks if the channel is
2187         /// public, and thus should be called whenever the result is going to be passed out in a
2188         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
2189         ///
2190         /// May be called with channel_state already locked!
2191         fn get_channel_update_for_broadcast(&self, chan: &Channel<<K::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2192                 if !chan.should_announce() {
2193                         return Err(LightningError {
2194                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
2195                                 action: msgs::ErrorAction::IgnoreError
2196                         });
2197                 }
2198                 if chan.get_short_channel_id().is_none() {
2199                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
2200                 }
2201                 log_trace!(self.logger, "Attempting to generate broadcast channel update for channel {}", log_bytes!(chan.channel_id()));
2202                 self.get_channel_update_for_unicast(chan)
2203         }
2204
2205         /// Gets the current channel_update for the given channel. This does not check if the channel
2206         /// is public (only returning an Err if the channel does not yet have an assigned short_id),
2207         /// and thus MUST NOT be called unless the recipient of the resulting message has already
2208         /// provided evidence that they know about the existence of the channel.
2209         /// May be called with channel_state already locked!
2210         fn get_channel_update_for_unicast(&self, chan: &Channel<<K::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2211                 log_trace!(self.logger, "Attempting to generate channel update for channel {}", log_bytes!(chan.channel_id()));
2212                 let short_channel_id = match chan.get_short_channel_id().or(chan.latest_inbound_scid_alias()) {
2213                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
2214                         Some(id) => id,
2215                 };
2216
2217                 self.get_channel_update_for_onion(short_channel_id, chan)
2218         }
2219         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<<K::Target as SignerProvider>::Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
2220                 log_trace!(self.logger, "Generating channel update for channel {}", log_bytes!(chan.channel_id()));
2221                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
2222
2223                 let unsigned = msgs::UnsignedChannelUpdate {
2224                         chain_hash: self.genesis_hash,
2225                         short_channel_id,
2226                         timestamp: chan.get_update_time_counter(),
2227                         flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
2228                         cltv_expiry_delta: chan.get_cltv_expiry_delta(),
2229                         htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
2230                         htlc_maximum_msat: chan.get_announced_htlc_max_msat(),
2231                         fee_base_msat: chan.get_outbound_forwarding_fee_base_msat(),
2232                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
2233                         excess_data: Vec::new(),
2234                 };
2235
2236                 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
2237                 let sig = self.secp_ctx.sign_ecdsa(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
2238
2239                 Ok(msgs::ChannelUpdate {
2240                         signature: sig,
2241                         contents: unsigned
2242                 })
2243         }
2244
2245         // Only public for testing, this should otherwise never be called direcly
2246         pub(crate) fn send_payment_along_path(&self, path: &Vec<RouteHop>, payment_params: &Option<PaymentParameters>, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option<PaymentPreimage>, session_priv_bytes: [u8; 32]) -> Result<(), APIError> {
2247                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
2248                 let prng_seed = self.keys_manager.get_secure_random_bytes();
2249                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
2250
2251                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
2252                         .map_err(|_| APIError::InvalidRoute{err: "Pubkey along hop was maliciously selected"})?;
2253                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height, keysend_preimage)?;
2254                 if onion_utils::route_size_insane(&onion_payloads) {
2255                         return Err(APIError::InvalidRoute{err: "Route size too large considering onion data"});
2256                 }
2257                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
2258
2259                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2260
2261                 let err: Result<(), _> = loop {
2262                         let id = match self.short_to_chan_info.read().unwrap().get(&path.first().unwrap().short_channel_id) {
2263                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
2264                                 Some((_cp_id, chan_id)) => chan_id.clone(),
2265                         };
2266
2267                         let mut channel_lock = self.channel_state.lock().unwrap();
2268                         let channel_state = &mut *channel_lock;
2269                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
2270                                 match {
2271                                         if chan.get().get_counterparty_node_id() != path.first().unwrap().pubkey {
2272                                                 return Err(APIError::InvalidRoute{err: "Node ID mismatch on first hop!"});
2273                                         }
2274                                         if !chan.get().is_live() {
2275                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
2276                                         }
2277                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(
2278                                                 htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
2279                                                         path: path.clone(),
2280                                                         session_priv: session_priv.clone(),
2281                                                         first_hop_htlc_msat: htlc_msat,
2282                                                         payment_id,
2283                                                         payment_secret: payment_secret.clone(),
2284                                                         payment_params: payment_params.clone(),
2285                                                 }, onion_packet, &self.logger),
2286                                                 chan)
2287                                 } {
2288                                         Some((update_add, commitment_signed, monitor_update)) => {
2289                                                 let update_err = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update);
2290                                                 let chan_id = chan.get().channel_id();
2291                                                 match (update_err,
2292                                                         handle_monitor_update_res!(self, update_err, chan,
2293                                                                 RAACommitmentOrder::CommitmentFirst, false, true))
2294                                                 {
2295                                                         (ChannelMonitorUpdateStatus::PermanentFailure, Err(e)) => break Err(e),
2296                                                         (ChannelMonitorUpdateStatus::Completed, Ok(())) => {},
2297                                                         (ChannelMonitorUpdateStatus::InProgress, Err(_)) => {
2298                                                                 // Note that MonitorUpdateInProgress here indicates (per function
2299                                                                 // docs) that we will resend the commitment update once monitor
2300                                                                 // updating completes. Therefore, we must return an error
2301                                                                 // indicating that it is unsafe to retry the payment wholesale,
2302                                                                 // which we do in the send_payment check for
2303                                                                 // MonitorUpdateInProgress, below.
2304                                                                 return Err(APIError::MonitorUpdateInProgress);
2305                                                         },
2306                                                         _ => unreachable!(),
2307                                                 }
2308
2309                                                 log_debug!(self.logger, "Sending payment along path resulted in a commitment_signed for channel {}", log_bytes!(chan_id));
2310                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2311                                                         node_id: path.first().unwrap().pubkey,
2312                                                         updates: msgs::CommitmentUpdate {
2313                                                                 update_add_htlcs: vec![update_add],
2314                                                                 update_fulfill_htlcs: Vec::new(),
2315                                                                 update_fail_htlcs: Vec::new(),
2316                                                                 update_fail_malformed_htlcs: Vec::new(),
2317                                                                 update_fee: None,
2318                                                                 commitment_signed,
2319                                                         },
2320                                                 });
2321                                         },
2322                                         None => { },
2323                                 }
2324                         } else {
2325                                 // The channel was likely removed after we fetched the id from the
2326                                 // `short_to_chan_info` map, but before we successfully locked the `by_id` map.
2327                                 // This can occur as no consistency guarantees exists between the two maps.
2328                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
2329                         }
2330                         return Ok(());
2331                 };
2332
2333                 match handle_error!(self, err, path.first().unwrap().pubkey) {
2334                         Ok(_) => unreachable!(),
2335                         Err(e) => {
2336                                 Err(APIError::ChannelUnavailable { err: e.err })
2337                         },
2338                 }
2339         }
2340
2341         /// Sends a payment along a given route.
2342         ///
2343         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
2344         /// fields for more info.
2345         ///
2346         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
2347         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
2348         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
2349         /// [`Event::PaymentSent`]) LDK will not stop you from sending a second payment with the same
2350         /// [`PaymentId`].
2351         ///
2352         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
2353         /// tracking of payments, including state to indicate once a payment has completed. Because you
2354         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
2355         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
2356         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
2357         ///
2358         /// May generate SendHTLCs message(s) event on success, which should be relayed (e.g. via
2359         /// [`PeerManager::process_events`]).
2360         ///
2361         /// Each path may have a different return value, and PaymentSendValue may return a Vec with
2362         /// each entry matching the corresponding-index entry in the route paths, see
2363         /// PaymentSendFailure for more info.
2364         ///
2365         /// In general, a path may raise:
2366         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
2367         ///    node public key) is specified.
2368         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available for updates
2369         ///    (including due to previous monitor update failure or new permanent monitor update
2370         ///    failure).
2371         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
2372         ///    relevant updates.
2373         ///
2374         /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
2375         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
2376         /// different route unless you intend to pay twice!
2377         ///
2378         /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
2379         /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
2380         /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
2381         /// must not contain multiple paths as multi-path payments require a recipient-provided
2382         /// payment_secret.
2383         ///
2384         /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
2385         /// bit set (either as required or as available). If multiple paths are present in the Route,
2386         /// we assume the invoice had the basic_mpp feature set.
2387         ///
2388         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2389         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
2390         pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
2391                 let best_block_height = self.best_block.read().unwrap().height();
2392                 self.pending_outbound_payments
2393                         .send_payment_with_route(route, payment_hash, payment_secret, payment_id, &self.keys_manager, best_block_height,
2394                                 |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2395                                 self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2396         }
2397
2398         #[cfg(test)]
2399         fn test_send_payment_internal(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>, onion_session_privs: Vec<[u8; 32]>) -> Result<(), PaymentSendFailure> {
2400                 let best_block_height = self.best_block.read().unwrap().height();
2401                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.keys_manager, best_block_height,
2402                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2403                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2404         }
2405
2406         #[cfg(test)]
2407         pub(crate) fn test_add_new_pending_payment(&self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId, route: &Route) -> Result<Vec<[u8; 32]>, PaymentSendFailure> {
2408                 let best_block_height = self.best_block.read().unwrap().height();
2409                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, payment_secret, payment_id, route, &self.keys_manager, best_block_height)
2410         }
2411
2412
2413         /// Retries a payment along the given [`Route`].
2414         ///
2415         /// Errors returned are a superset of those returned from [`send_payment`], so see
2416         /// [`send_payment`] documentation for more details on errors. This method will also error if the
2417         /// retry amount puts the payment more than 10% over the payment's total amount, if the payment
2418         /// for the given `payment_id` cannot be found (likely due to timeout or success), or if
2419         /// further retries have been disabled with [`abandon_payment`].
2420         ///
2421         /// [`send_payment`]: [`ChannelManager::send_payment`]
2422         /// [`abandon_payment`]: [`ChannelManager::abandon_payment`]
2423         pub fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
2424                 let best_block_height = self.best_block.read().unwrap().height();
2425                 self.pending_outbound_payments.retry_payment_with_route(route, payment_id, &self.keys_manager, best_block_height,
2426                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2427                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2428         }
2429
2430         /// Signals that no further retries for the given payment will occur.
2431         ///
2432         /// After this method returns, no future calls to [`retry_payment`] for the given `payment_id`
2433         /// are allowed. If no [`Event::PaymentFailed`] event had been generated before, one will be
2434         /// generated as soon as there are no remaining pending HTLCs for this payment.
2435         ///
2436         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
2437         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
2438         /// determine the ultimate status of a payment.
2439         ///
2440         /// If an [`Event::PaymentFailed`] event is generated and we restart without this
2441         /// [`ChannelManager`] having been persisted, the payment may still be in the pending state
2442         /// upon restart. This allows further calls to [`retry_payment`] (and requiring a second call
2443         /// to [`abandon_payment`] to mark the payment as failed again). Otherwise, future calls to
2444         /// [`retry_payment`] will fail with [`PaymentSendFailure::ParameterError`].
2445         ///
2446         /// [`abandon_payment`]: Self::abandon_payment
2447         /// [`retry_payment`]: Self::retry_payment
2448         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
2449         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2450         pub fn abandon_payment(&self, payment_id: PaymentId) {
2451                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2452                 if let Some(payment_failed_ev) = self.pending_outbound_payments.abandon_payment(payment_id) {
2453                         self.pending_events.lock().unwrap().push(payment_failed_ev);
2454                 }
2455         }
2456
2457         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
2458         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
2459         /// the preimage, it must be a cryptographically secure random value that no intermediate node
2460         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
2461         /// never reach the recipient.
2462         ///
2463         /// See [`send_payment`] documentation for more details on the return value of this function
2464         /// and idempotency guarantees provided by the [`PaymentId`] key.
2465         ///
2466         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
2467         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
2468         ///
2469         /// Note that `route` must have exactly one path.
2470         ///
2471         /// [`send_payment`]: Self::send_payment
2472         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
2473                 let best_block_height = self.best_block.read().unwrap().height();
2474                 self.pending_outbound_payments.send_spontaneous_payment(route, payment_preimage, payment_id, &self.keys_manager, best_block_height,
2475                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2476                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2477         }
2478
2479         /// Send a payment that is probing the given route for liquidity. We calculate the
2480         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
2481         /// us to easily discern them from real payments.
2482         pub fn send_probe(&self, hops: Vec<RouteHop>) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
2483                 let best_block_height = self.best_block.read().unwrap().height();
2484                 self.pending_outbound_payments.send_probe(hops, self.probing_cookie_secret, &self.keys_manager, best_block_height,
2485                         |path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv|
2486                         self.send_payment_along_path(path, payment_params, payment_hash, payment_secret, total_value, cur_height, payment_id, keysend_preimage, session_priv))
2487         }
2488
2489         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
2490         /// payment probe.
2491         #[cfg(test)]
2492         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
2493                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
2494         }
2495
2496         /// Handles the generation of a funding transaction, optionally (for tests) with a function
2497         /// which checks the correctness of the funding transaction given the associated channel.
2498         fn funding_transaction_generated_intern<FundingOutput: Fn(&Channel<<K::Target as SignerProvider>::Signer>, &Transaction) -> Result<OutPoint, APIError>>(
2499                 &self, temporary_channel_id: &[u8; 32], _counterparty_node_id: &PublicKey, funding_transaction: Transaction, find_funding_output: FundingOutput
2500         ) -> Result<(), APIError> {
2501                 let (chan, msg) = {
2502                         let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
2503                                 Some(mut chan) => {
2504                                         let funding_txo = find_funding_output(&chan, &funding_transaction)?;
2505
2506                                         (chan.get_outbound_funding_created(funding_transaction, funding_txo, &self.logger)
2507                                                 .map_err(|e| if let ChannelError::Close(msg) = e {
2508                                                         MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.get_user_id(), chan.force_shutdown(true), None)
2509                                                 } else { unreachable!(); })
2510                                         , chan)
2511                                 },
2512                                 None => { return Err(APIError::ChannelUnavailable { err: "No such channel".to_owned() }) },
2513                         };
2514                         match handle_error!(self, res, chan.get_counterparty_node_id()) {
2515                                 Ok(funding_msg) => {
2516                                         (chan, funding_msg)
2517                                 },
2518                                 Err(_) => { return Err(APIError::ChannelUnavailable {
2519                                         err: "Error deriving keys or signing initial commitment transactions - either our RNG or our counterparty's RNG is broken or the Signer refused to sign".to_owned()
2520                                 }) },
2521                         }
2522                 };
2523
2524                 let mut channel_state = self.channel_state.lock().unwrap();
2525                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
2526                         node_id: chan.get_counterparty_node_id(),
2527                         msg,
2528                 });
2529                 match channel_state.by_id.entry(chan.channel_id()) {
2530                         hash_map::Entry::Occupied(_) => {
2531                                 panic!("Generated duplicate funding txid?");
2532                         },
2533                         hash_map::Entry::Vacant(e) => {
2534                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
2535                                 if id_to_peer.insert(chan.channel_id(), chan.get_counterparty_node_id()).is_some() {
2536                                         panic!("id_to_peer map already contained funding txid, which shouldn't be possible");
2537                                 }
2538                                 e.insert(chan);
2539                         }
2540                 }
2541                 Ok(())
2542         }
2543
2544         #[cfg(test)]
2545         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> {
2546                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |_, tx| {
2547                         Ok(OutPoint { txid: tx.txid(), index: output_index })
2548                 })
2549         }
2550
2551         /// Call this upon creation of a funding transaction for the given channel.
2552         ///
2553         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
2554         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
2555         ///
2556         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
2557         /// across the p2p network.
2558         ///
2559         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
2560         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
2561         ///
2562         /// May panic if the output found in the funding transaction is duplicative with some other
2563         /// channel (note that this should be trivially prevented by using unique funding transaction
2564         /// keys per-channel).
2565         ///
2566         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
2567         /// counterparty's signature the funding transaction will automatically be broadcast via the
2568         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
2569         ///
2570         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
2571         /// not currently support replacing a funding transaction on an existing channel. Instead,
2572         /// create a new channel with a conflicting funding transaction.
2573         ///
2574         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
2575         /// the wallet software generating the funding transaction to apply anti-fee sniping as
2576         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
2577         /// for more details.
2578         ///
2579         /// [`Event::FundingGenerationReady`]: crate::util::events::Event::FundingGenerationReady
2580         /// [`Event::ChannelClosed`]: crate::util::events::Event::ChannelClosed
2581         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
2582                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2583
2584                 for inp in funding_transaction.input.iter() {
2585                         if inp.witness.is_empty() {
2586                                 return Err(APIError::APIMisuseError {
2587                                         err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
2588                                 });
2589                         }
2590                 }
2591                 {
2592                         let height = self.best_block.read().unwrap().height();
2593                         // Transactions are evaluated as final by network mempools at the next block. However, the modules
2594                         // constituting our Lightning node might not have perfect sync about their blockchain views. Thus, if
2595                         // the wallet module is in advance on the LDK view, allow one more block of headroom.
2596                         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 + 2 {
2597                                 return Err(APIError::APIMisuseError {
2598                                         err: "Funding transaction absolute timelock is non-final".to_owned()
2599                                 });
2600                         }
2601                 }
2602                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, |chan, tx| {
2603                         let mut output_index = None;
2604                         let expected_spk = chan.get_funding_redeemscript().to_v0_p2wsh();
2605                         for (idx, outp) in tx.output.iter().enumerate() {
2606                                 if outp.script_pubkey == expected_spk && outp.value == chan.get_value_satoshis() {
2607                                         if output_index.is_some() {
2608                                                 return Err(APIError::APIMisuseError {
2609                                                         err: "Multiple outputs matched the expected script and value".to_owned()
2610                                                 });
2611                                         }
2612                                         if idx > u16::max_value() as usize {
2613                                                 return Err(APIError::APIMisuseError {
2614                                                         err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
2615                                                 });
2616                                         }
2617                                         output_index = Some(idx as u16);
2618                                 }
2619                         }
2620                         if output_index.is_none() {
2621                                 return Err(APIError::APIMisuseError {
2622                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
2623                                 });
2624                         }
2625                         Ok(OutPoint { txid: tx.txid(), index: output_index.unwrap() })
2626                 })
2627         }
2628
2629         /// Atomically updates the [`ChannelConfig`] for the given channels.
2630         ///
2631         /// Once the updates are applied, each eligible channel (advertised with a known short channel
2632         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
2633         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
2634         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
2635         ///
2636         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
2637         /// `counterparty_node_id` is provided.
2638         ///
2639         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
2640         /// below [`MIN_CLTV_EXPIRY_DELTA`].
2641         ///
2642         /// If an error is returned, none of the updates should be considered applied.
2643         ///
2644         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
2645         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
2646         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
2647         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2648         /// [`ChannelUpdate`]: msgs::ChannelUpdate
2649         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2650         /// [`APIMisuseError`]: APIError::APIMisuseError
2651         pub fn update_channel_config(
2652                 &self, counterparty_node_id: &PublicKey, channel_ids: &[[u8; 32]], config: &ChannelConfig,
2653         ) -> Result<(), APIError> {
2654                 if config.cltv_expiry_delta < MIN_CLTV_EXPIRY_DELTA {
2655                         return Err(APIError::APIMisuseError {
2656                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
2657                         });
2658                 }
2659
2660                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(
2661                         &self.total_consistency_lock, &self.persistence_notifier,
2662                 );
2663                 {
2664                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2665                         let channel_state = &mut *channel_state_lock;
2666                         for channel_id in channel_ids {
2667                                 let channel_counterparty_node_id = channel_state.by_id.get(channel_id)
2668                                         .ok_or(APIError::ChannelUnavailable {
2669                                                 err: format!("Channel with ID {} was not found", log_bytes!(*channel_id)),
2670                                         })?
2671                                         .get_counterparty_node_id();
2672                                 if channel_counterparty_node_id != *counterparty_node_id {
2673                                         return Err(APIError::APIMisuseError {
2674                                                 err: "counterparty node id mismatch".to_owned(),
2675                                         });
2676                                 }
2677                         }
2678                         for channel_id in channel_ids {
2679                                 let channel = channel_state.by_id.get_mut(channel_id).unwrap();
2680                                 if !channel.update_config(config) {
2681                                         continue;
2682                                 }
2683                                 if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
2684                                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
2685                                 } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
2686                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
2687                                                 node_id: channel.get_counterparty_node_id(),
2688                                                 msg,
2689                                         });
2690                                 }
2691                         }
2692                 }
2693                 Ok(())
2694         }
2695
2696         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
2697         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
2698         ///
2699         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
2700         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
2701         ///
2702         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
2703         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
2704         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
2705         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
2706         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
2707         ///
2708         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
2709         /// you from forwarding more than you received.
2710         ///
2711         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
2712         /// backwards.
2713         ///
2714         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
2715         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
2716         // TODO: when we move to deciding the best outbound channel at forward time, only take
2717         // `next_node_id` and not `next_hop_channel_id`
2718         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> {
2719                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2720
2721                 let next_hop_scid = match self.channel_state.lock().unwrap().by_id.get(next_hop_channel_id) {
2722                         Some(chan) => {
2723                                 if !chan.is_usable() {
2724                                         return Err(APIError::ChannelUnavailable {
2725                                                 err: format!("Channel with id {} not fully established", log_bytes!(*next_hop_channel_id))
2726                                         })
2727                                 }
2728                                 chan.get_short_channel_id().unwrap_or(chan.outbound_scid_alias())
2729                         },
2730                         None => return Err(APIError::ChannelUnavailable {
2731                                 err: format!("Channel with id {} not found", log_bytes!(*next_hop_channel_id))
2732                         })
2733                 };
2734
2735                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
2736                         .ok_or_else(|| APIError::APIMisuseError {
2737                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
2738                         })?;
2739
2740                 let routing = match payment.forward_info.routing {
2741                         PendingHTLCRouting::Forward { onion_packet, .. } => {
2742                                 PendingHTLCRouting::Forward { onion_packet, short_channel_id: next_hop_scid }
2743                         },
2744                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
2745                 };
2746                 let pending_htlc_info = PendingHTLCInfo {
2747                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
2748                 };
2749
2750                 let mut per_source_pending_forward = [(
2751                         payment.prev_short_channel_id,
2752                         payment.prev_funding_outpoint,
2753                         payment.prev_user_channel_id,
2754                         vec![(pending_htlc_info, payment.prev_htlc_id)]
2755                 )];
2756                 self.forward_htlcs(&mut per_source_pending_forward);
2757                 Ok(())
2758         }
2759
2760         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
2761         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
2762         ///
2763         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
2764         /// backwards.
2765         ///
2766         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
2767         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
2768                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2769
2770                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
2771                         .ok_or_else(|| APIError::APIMisuseError {
2772                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
2773                         })?;
2774
2775                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
2776                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
2777                                 short_channel_id: payment.prev_short_channel_id,
2778                                 outpoint: payment.prev_funding_outpoint,
2779                                 htlc_id: payment.prev_htlc_id,
2780                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
2781                                 phantom_shared_secret: None,
2782                         });
2783
2784                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
2785                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
2786                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
2787                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
2788
2789                 Ok(())
2790         }
2791
2792         /// Processes HTLCs which are pending waiting on random forward delay.
2793         ///
2794         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
2795         /// Will likely generate further events.
2796         pub fn process_pending_htlc_forwards(&self) {
2797                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2798
2799                 let mut new_events = Vec::new();
2800                 let mut failed_forwards = Vec::new();
2801                 let mut phantom_receives: Vec<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
2802                 {
2803                         let mut forward_htlcs = HashMap::new();
2804                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
2805
2806                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
2807                                 if short_chan_id != 0 {
2808                                         macro_rules! forwarding_channel_not_found {
2809                                                 () => {
2810                                                         for forward_info in pending_forwards.drain(..) {
2811                                                                 match forward_info {
2812                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
2813                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
2814                                                                                 forward_info: PendingHTLCInfo {
2815                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
2816                                                                                         outgoing_cltv_value, incoming_amt_msat: _
2817                                                                                 }
2818                                                                         }) => {
2819                                                                                 macro_rules! failure_handler {
2820                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
2821                                                                                                 log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
2822
2823                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
2824                                                                                                         short_channel_id: prev_short_channel_id,
2825                                                                                                         outpoint: prev_funding_outpoint,
2826                                                                                                         htlc_id: prev_htlc_id,
2827                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
2828                                                                                                         phantom_shared_secret: $phantom_ss,
2829                                                                                                 });
2830
2831                                                                                                 let reason = if $next_hop_unknown {
2832                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
2833                                                                                                 } else {
2834                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
2835                                                                                                 };
2836
2837                                                                                                 failed_forwards.push((htlc_source, payment_hash,
2838                                                                                                         HTLCFailReason::reason($err_code, $err_data),
2839                                                                                                         reason
2840                                                                                                 ));
2841                                                                                                 continue;
2842                                                                                         }
2843                                                                                 }
2844                                                                                 macro_rules! fail_forward {
2845                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
2846                                                                                                 {
2847                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
2848                                                                                                 }
2849                                                                                         }
2850                                                                                 }
2851                                                                                 macro_rules! failed_payment {
2852                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
2853                                                                                                 {
2854                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
2855                                                                                                 }
2856                                                                                         }
2857                                                                                 }
2858                                                                                 if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
2859                                                                                         let phantom_secret_res = self.keys_manager.get_node_secret(Recipient::PhantomNode);
2860                                                                                         if phantom_secret_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.genesis_hash) {
2861                                                                                                 let phantom_shared_secret = SharedSecret::new(&onion_packet.public_key.unwrap(), &phantom_secret_res.unwrap()).secret_bytes();
2862                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
2863                                                                                                         Ok(res) => res,
2864                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
2865                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();
2866                                                                                                                 // In this scenario, the phantom would have sent us an
2867                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
2868                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
2869                                                                                                                 // of the onion.
2870                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
2871                                                                                                         },
2872                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
2873                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
2874                                                                                                         },
2875                                                                                                 };
2876                                                                                                 match next_hop {
2877                                                                                                         onion_utils::Hop::Receive(hop_data) => {
2878                                                                                                                 match self.construct_recv_pending_htlc_info(hop_data, incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value, Some(phantom_shared_secret)) {
2879                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, vec![(info, prev_htlc_id)])),
2880                                                                                                                         Err(ReceiveError { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
2881                                                                                                                 }
2882                                                                                                         },
2883                                                                                                         _ => panic!(),
2884                                                                                                 }
2885                                                                                         } else {
2886                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
2887                                                                                         }
2888                                                                                 } else {
2889                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
2890                                                                                 }
2891                                                                         },
2892                                                                         HTLCForwardInfo::FailHTLC { .. } => {
2893                                                                                 // Channel went away before we could fail it. This implies
2894                                                                                 // the channel is now on chain and our counterparty is
2895                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
2896                                                                                 // problem, not ours.
2897                                                                         }
2898                                                                 }
2899                                                         }
2900                                                 }
2901                                         }
2902                                         let forward_chan_id = match self.short_to_chan_info.read().unwrap().get(&short_chan_id) {
2903                                                 Some((_cp_id, chan_id)) => chan_id.clone(),
2904                                                 None => {
2905                                                         forwarding_channel_not_found!();
2906                                                         continue;
2907                                                 }
2908                                         };
2909                                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2910                                         let channel_state = &mut *channel_state_lock;
2911                                         match channel_state.by_id.entry(forward_chan_id) {
2912                                                 hash_map::Entry::Vacant(_) => {
2913                                                         forwarding_channel_not_found!();
2914                                                         continue;
2915                                                 },
2916                                                 hash_map::Entry::Occupied(mut chan) => {
2917                                                         for forward_info in pending_forwards.drain(..) {
2918                                                                 match forward_info {
2919                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
2920                                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id: _,
2921                                                                                 forward_info: PendingHTLCInfo {
2922                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
2923                                                                                         routing: PendingHTLCRouting::Forward { onion_packet, .. }, incoming_amt_msat: _,
2924                                                                                 },
2925                                                                         }) => {
2926                                                                                 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);
2927                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
2928                                                                                         short_channel_id: prev_short_channel_id,
2929                                                                                         outpoint: prev_funding_outpoint,
2930                                                                                         htlc_id: prev_htlc_id,
2931                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
2932                                                                                         // Phantom payments are only PendingHTLCRouting::Receive.
2933                                                                                         phantom_shared_secret: None,
2934                                                                                 });
2935                                                                                 if let Err(e) = chan.get_mut().queue_add_htlc(outgoing_amt_msat,
2936                                                                                         payment_hash, outgoing_cltv_value, htlc_source.clone(),
2937                                                                                         onion_packet, &self.logger)
2938                                                                                 {
2939                                                                                         if let ChannelError::Ignore(msg) = e {
2940                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
2941                                                                                         } else {
2942                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
2943                                                                                         }
2944                                                                                         let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan.get());
2945                                                                                         failed_forwards.push((htlc_source, payment_hash,
2946                                                                                                 HTLCFailReason::reason(failure_code, data),
2947                                                                                                 HTLCDestination::NextHopChannel { node_id: Some(chan.get().get_counterparty_node_id()), channel_id: forward_chan_id }
2948                                                                                         ));
2949                                                                                         continue;
2950                                                                                 }
2951                                                                         },
2952                                                                         HTLCForwardInfo::AddHTLC { .. } => {
2953                                                                                 panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
2954                                                                         },
2955                                                                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
2956                                                                                 log_trace!(self.logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
2957                                                                                 if let Err(e) = chan.get_mut().queue_fail_htlc(
2958                                                                                         htlc_id, err_packet, &self.logger
2959                                                                                 ) {
2960                                                                                         if let ChannelError::Ignore(msg) = e {
2961                                                                                                 log_trace!(self.logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
2962                                                                                         } else {
2963                                                                                                 panic!("Stated return value requirements in queue_fail_htlc() were not met");
2964                                                                                         }
2965                                                                                         // fail-backs are best-effort, we probably already have one
2966                                                                                         // pending, and if not that's OK, if not, the channel is on
2967                                                                                         // the chain and sending the HTLC-Timeout is their problem.
2968                                                                                         continue;
2969                                                                                 }
2970                                                                         },
2971                                                                 }
2972                                                         }
2973                                                 }
2974                                         }
2975                                 } else {
2976                                         for forward_info in pending_forwards.drain(..) {
2977                                                 match forward_info {
2978                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
2979                                                                 prev_short_channel_id, prev_htlc_id, prev_funding_outpoint, prev_user_channel_id,
2980                                                                 forward_info: PendingHTLCInfo {
2981                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat, ..
2982                                                                 }
2983                                                         }) => {
2984                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret) = match routing {
2985                                                                         PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry, phantom_shared_secret } => {
2986                                                                                 let _legacy_hop_data = Some(payment_data.clone());
2987                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data }, Some(payment_data), phantom_shared_secret)
2988                                                                         },
2989                                                                         PendingHTLCRouting::ReceiveKeysend { payment_preimage, incoming_cltv_expiry } =>
2990                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage), None, None),
2991                                                                         _ => {
2992                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
2993                                                                         }
2994                                                                 };
2995                                                                 let claimable_htlc = ClaimableHTLC {
2996                                                                         prev_hop: HTLCPreviousHopData {
2997                                                                                 short_channel_id: prev_short_channel_id,
2998                                                                                 outpoint: prev_funding_outpoint,
2999                                                                                 htlc_id: prev_htlc_id,
3000                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
3001                                                                                 phantom_shared_secret,
3002                                                                         },
3003                                                                         value: outgoing_amt_msat,
3004                                                                         timer_ticks: 0,
3005                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
3006                                                                         cltv_expiry,
3007                                                                         onion_payload,
3008                                                                 };
3009
3010                                                                 macro_rules! fail_htlc {
3011                                                                         ($htlc: expr, $payment_hash: expr) => {
3012                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
3013                                                                                 htlc_msat_height_data.extend_from_slice(
3014                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
3015                                                                                 );
3016                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
3017                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
3018                                                                                                 outpoint: prev_funding_outpoint,
3019                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
3020                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
3021                                                                                                 phantom_shared_secret,
3022                                                                                         }), payment_hash,
3023                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
3024                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
3025                                                                                 ));
3026                                                                         }
3027                                                                 }
3028                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
3029                                                                 let mut receiver_node_id = self.our_network_pubkey;
3030                                                                 if phantom_shared_secret.is_some() {
3031                                                                         receiver_node_id = self.keys_manager.get_node_id(Recipient::PhantomNode)
3032                                                                                 .expect("Failed to get node_id for phantom node recipient");
3033                                                                 }
3034
3035                                                                 macro_rules! check_total_value {
3036                                                                         ($payment_data: expr, $payment_preimage: expr) => {{
3037                                                                                 let mut payment_claimable_generated = false;
3038                                                                                 let purpose = || {
3039                                                                                         events::PaymentPurpose::InvoicePayment {
3040                                                                                                 payment_preimage: $payment_preimage,
3041                                                                                                 payment_secret: $payment_data.payment_secret,
3042                                                                                         }
3043                                                                                 };
3044                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
3045                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3046                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3047                                                                                         continue
3048                                                                                 }
3049                                                                                 let (_, htlcs) = claimable_payments.claimable_htlcs.entry(payment_hash)
3050                                                                                         .or_insert_with(|| (purpose(), Vec::new()));
3051                                                                                 if htlcs.len() == 1 {
3052                                                                                         if let OnionPayload::Spontaneous(_) = htlcs[0].onion_payload {
3053                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as we already had an existing keysend HTLC with the same payment hash", log_bytes!(payment_hash.0));
3054                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3055                                                                                                 continue
3056                                                                                         }
3057                                                                                 }
3058                                                                                 let mut total_value = claimable_htlc.value;
3059                                                                                 for htlc in htlcs.iter() {
3060                                                                                         total_value += htlc.value;
3061                                                                                         match &htlc.onion_payload {
3062                                                                                                 OnionPayload::Invoice { .. } => {
3063                                                                                                         if htlc.total_msat != $payment_data.total_msat {
3064                                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
3065                                                                                                                         log_bytes!(payment_hash.0), $payment_data.total_msat, htlc.total_msat);
3066                                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
3067                                                                                                         }
3068                                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
3069                                                                                                 },
3070                                                                                                 _ => unreachable!(),
3071                                                                                         }
3072                                                                                 }
3073                                                                                 if total_value >= msgs::MAX_VALUE_MSAT || total_value > $payment_data.total_msat {
3074                                                                                         log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the total value {} ran over expected value {} (or HTLCs were inconsistent)",
3075                                                                                                 log_bytes!(payment_hash.0), total_value, $payment_data.total_msat);
3076                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3077                                                                                 } else if total_value == $payment_data.total_msat {
3078                                                                                         let prev_channel_id = prev_funding_outpoint.to_channel_id();
3079                                                                                         htlcs.push(claimable_htlc);
3080                                                                                         new_events.push(events::Event::PaymentClaimable {
3081                                                                                                 receiver_node_id: Some(receiver_node_id),
3082                                                                                                 payment_hash,
3083                                                                                                 purpose: purpose(),
3084                                                                                                 amount_msat: total_value,
3085                                                                                                 via_channel_id: Some(prev_channel_id),
3086                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
3087                                                                                         });
3088                                                                                         payment_claimable_generated = true;
3089                                                                                 } else {
3090                                                                                         // Nothing to do - we haven't reached the total
3091                                                                                         // payment value yet, wait until we receive more
3092                                                                                         // MPP parts.
3093                                                                                         htlcs.push(claimable_htlc);
3094                                                                                 }
3095                                                                                 payment_claimable_generated
3096                                                                         }}
3097                                                                 }
3098
3099                                                                 // Check that the payment hash and secret are known. Note that we
3100                                                                 // MUST take care to handle the "unknown payment hash" and
3101                                                                 // "incorrect payment secret" cases here identically or we'd expose
3102                                                                 // that we are the ultimate recipient of the given payment hash.
3103                                                                 // Further, we must not expose whether we have any other HTLCs
3104                                                                 // associated with the same payment_hash pending or not.
3105                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
3106                                                                 match payment_secrets.entry(payment_hash) {
3107                                                                         hash_map::Entry::Vacant(_) => {
3108                                                                                 match claimable_htlc.onion_payload {
3109                                                                                         OnionPayload::Invoice { .. } => {
3110                                                                                                 let payment_data = payment_data.unwrap();
3111                                                                                                 let payment_preimage = match inbound_payment::verify(payment_hash, &payment_data, self.highest_seen_timestamp.load(Ordering::Acquire) as u64, &self.inbound_payment_key, &self.logger) {
3112                                                                                                         Ok(payment_preimage) => payment_preimage,
3113                                                                                                         Err(()) => {
3114                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3115                                                                                                                 continue
3116                                                                                                         }
3117                                                                                                 };
3118                                                                                                 check_total_value!(payment_data, payment_preimage);
3119                                                                                         },
3120                                                                                         OnionPayload::Spontaneous(preimage) => {
3121                                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
3122                                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3123                                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3124                                                                                                         continue
3125                                                                                                 }
3126                                                                                                 match claimable_payments.claimable_htlcs.entry(payment_hash) {
3127                                                                                                         hash_map::Entry::Vacant(e) => {
3128                                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
3129                                                                                                                 e.insert((purpose.clone(), vec![claimable_htlc]));
3130                                                                                                                 let prev_channel_id = prev_funding_outpoint.to_channel_id();
3131                                                                                                                 new_events.push(events::Event::PaymentClaimable {
3132                                                                                                                         receiver_node_id: Some(receiver_node_id),
3133                                                                                                                         payment_hash,
3134                                                                                                                         amount_msat: outgoing_amt_msat,
3135                                                                                                                         purpose,
3136                                                                                                                         via_channel_id: Some(prev_channel_id),
3137                                                                                                                         via_user_channel_id: Some(prev_user_channel_id),
3138                                                                                                                 });
3139                                                                                                         },
3140                                                                                                         hash_map::Entry::Occupied(_) => {
3141                                                                                                                 log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} for a duplicative payment hash", log_bytes!(payment_hash.0));
3142                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
3143                                                                                                         }
3144                                                                                                 }
3145                                                                                         }
3146                                                                                 }
3147                                                                         },
3148                                                                         hash_map::Entry::Occupied(inbound_payment) => {
3149                                                                                 if payment_data.is_none() {
3150                                                                                         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));
3151                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3152                                                                                         continue
3153                                                                                 };
3154                                                                                 let payment_data = payment_data.unwrap();
3155                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
3156                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", log_bytes!(payment_hash.0));
3157                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3158                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
3159                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
3160                                                                                                 log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
3161                                                                                         fail_htlc!(claimable_htlc, payment_hash);
3162                                                                                 } else {
3163                                                                                         let payment_claimable_generated = check_total_value!(payment_data, inbound_payment.get().payment_preimage);
3164                                                                                         if payment_claimable_generated {
3165                                                                                                 inbound_payment.remove_entry();
3166                                                                                         }
3167                                                                                 }
3168                                                                         },
3169                                                                 };
3170                                                         },
3171                                                         HTLCForwardInfo::FailHTLC { .. } => {
3172                                                                 panic!("Got pending fail of our own HTLC");
3173                                                         }
3174                                                 }
3175                                         }
3176                                 }
3177                         }
3178                 }
3179
3180                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
3181                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
3182                 }
3183                 self.forward_htlcs(&mut phantom_receives);
3184
3185                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
3186                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
3187                 // nice to do the work now if we can rather than while we're trying to get messages in the
3188                 // network stack.
3189                 self.check_free_holding_cells();
3190
3191                 if new_events.is_empty() { return }
3192                 let mut events = self.pending_events.lock().unwrap();
3193                 events.append(&mut new_events);
3194         }
3195
3196         /// Free the background events, generally called from timer_tick_occurred.
3197         ///
3198         /// Exposed for testing to allow us to process events quickly without generating accidental
3199         /// BroadcastChannelUpdate events in timer_tick_occurred.
3200         ///
3201         /// Expects the caller to have a total_consistency_lock read lock.
3202         fn process_background_events(&self) -> bool {
3203                 let mut background_events = Vec::new();
3204                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
3205                 if background_events.is_empty() {
3206                         return false;
3207                 }
3208
3209                 for event in background_events.drain(..) {
3210                         match event {
3211                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
3212                                         // The channel has already been closed, so no use bothering to care about the
3213                                         // monitor updating completing.
3214                                         let _ = self.chain_monitor.update_channel(funding_txo, update);
3215                                 },
3216                         }
3217                 }
3218                 true
3219         }
3220
3221         #[cfg(any(test, feature = "_test_utils"))]
3222         /// Process background events, for functional testing
3223         pub fn test_process_background_events(&self) {
3224                 self.process_background_events();
3225         }
3226
3227         fn update_channel_fee(&self, chan_id: &[u8; 32], chan: &mut Channel<<K::Target as SignerProvider>::Signer>, new_feerate: u32) -> NotifyOption {
3228                 if !chan.is_outbound() { return NotifyOption::SkipPersist; }
3229                 // If the feerate has decreased by less than half, don't bother
3230                 if new_feerate <= chan.get_feerate() && new_feerate * 2 > chan.get_feerate() {
3231                         log_trace!(self.logger, "Channel {} does not qualify for a feerate change from {} to {}.",
3232                                 log_bytes!(chan_id[..]), chan.get_feerate(), new_feerate);
3233                         return NotifyOption::SkipPersist;
3234                 }
3235                 if !chan.is_live() {
3236                         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).",
3237                                 log_bytes!(chan_id[..]), chan.get_feerate(), new_feerate);
3238                         return NotifyOption::SkipPersist;
3239                 }
3240                 log_trace!(self.logger, "Channel {} qualifies for a feerate change from {} to {}.",
3241                         log_bytes!(chan_id[..]), chan.get_feerate(), new_feerate);
3242
3243                 chan.queue_update_fee(new_feerate, &self.logger);
3244                 NotifyOption::DoPersist
3245         }
3246
3247         #[cfg(fuzzing)]
3248         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
3249         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
3250         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
3251         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
3252         pub fn maybe_update_chan_fees(&self) {
3253                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3254                         let mut should_persist = NotifyOption::SkipPersist;
3255
3256                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
3257
3258                         let mut channel_state = self.channel_state.lock().unwrap();
3259                         for (chan_id, chan) in channel_state.by_id.iter_mut() {
3260                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
3261                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
3262                         }
3263
3264                         should_persist
3265                 });
3266         }
3267
3268         /// Performs actions which should happen on startup and roughly once per minute thereafter.
3269         ///
3270         /// This currently includes:
3271         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
3272         ///  * Broadcasting `ChannelUpdate` messages if we've been disconnected from our peer for more
3273         ///    than a minute, informing the network that they should no longer attempt to route over
3274         ///    the channel.
3275         ///  * Expiring a channel's previous `ChannelConfig` if necessary to only allow forwarding HTLCs
3276         ///    with the current `ChannelConfig`.
3277         ///
3278         /// Note that this may cause reentrancy through `chain::Watch::update_channel` calls or feerate
3279         /// estimate fetches.
3280         pub fn timer_tick_occurred(&self) {
3281                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
3282                         let mut should_persist = NotifyOption::SkipPersist;
3283                         if self.process_background_events() { should_persist = NotifyOption::DoPersist; }
3284
3285                         let new_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
3286
3287                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
3288                         let mut timed_out_mpp_htlcs = Vec::new();
3289                         {
3290                                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3291                                 let channel_state = &mut *channel_state_lock;
3292                                 let pending_msg_events = &mut channel_state.pending_msg_events;
3293                                 channel_state.by_id.retain(|chan_id, chan| {
3294                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
3295                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
3296
3297                                         if let Err(e) = chan.timer_check_closing_negotiation_progress() {
3298                                                 let (needs_close, err) = convert_chan_err!(self, e, chan, chan_id);
3299                                                 handle_errors.push((Err(err), chan.get_counterparty_node_id()));
3300                                                 if needs_close { return false; }
3301                                         }
3302
3303                                         match chan.channel_update_status() {
3304                                                 ChannelUpdateStatus::Enabled if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged),
3305                                                 ChannelUpdateStatus::Disabled if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged),
3306                                                 ChannelUpdateStatus::DisabledStaged if chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
3307                                                 ChannelUpdateStatus::EnabledStaged if !chan.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
3308                                                 ChannelUpdateStatus::DisabledStaged if !chan.is_live() => {
3309                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
3310                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3311                                                                         msg: update
3312                                                                 });
3313                                                         }
3314                                                         should_persist = NotifyOption::DoPersist;
3315                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
3316                                                 },
3317                                                 ChannelUpdateStatus::EnabledStaged if chan.is_live() => {
3318                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
3319                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3320                                                                         msg: update
3321                                                                 });
3322                                                         }
3323                                                         should_persist = NotifyOption::DoPersist;
3324                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
3325                                                 },
3326                                                 _ => {},
3327                                         }
3328
3329                                         chan.maybe_expire_prev_config();
3330
3331                                         true
3332                                 });
3333                         }
3334
3335                         self.claimable_payments.lock().unwrap().claimable_htlcs.retain(|payment_hash, (_, htlcs)| {
3336                                 if htlcs.is_empty() {
3337                                         // This should be unreachable
3338                                         debug_assert!(false);
3339                                         return false;
3340                                 }
3341                                 if let OnionPayload::Invoice { .. } = htlcs[0].onion_payload {
3342                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
3343                                         // In this case we're not going to handle any timeouts of the parts here.
3344                                         if htlcs[0].total_msat == htlcs.iter().fold(0, |total, htlc| total + htlc.value) {
3345                                                 return true;
3346                                         } else if htlcs.into_iter().any(|htlc| {
3347                                                 htlc.timer_ticks += 1;
3348                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
3349                                         }) {
3350                                                 timed_out_mpp_htlcs.extend(htlcs.drain(..).map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
3351                                                 return false;
3352                                         }
3353                                 }
3354                                 true
3355                         });
3356
3357                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
3358                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
3359                                 let reason = HTLCFailReason::from_failure_code(23);
3360                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
3361                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
3362                         }
3363
3364                         for (err, counterparty_node_id) in handle_errors.drain(..) {
3365                                 let _ = handle_error!(self, err, counterparty_node_id);
3366                         }
3367
3368                         self.pending_outbound_payments.remove_stale_resolved_payments(&self.pending_events);
3369
3370                         // Technically we don't need to do this here, but if we have holding cell entries in a
3371                         // channel that need freeing, it's better to do that here and block a background task
3372                         // than block the message queueing pipeline.
3373                         if self.check_free_holding_cells() {
3374                                 should_persist = NotifyOption::DoPersist;
3375                         }
3376
3377                         should_persist
3378                 });
3379         }
3380
3381         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
3382         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
3383         /// along the path (including in our own channel on which we received it).
3384         ///
3385         /// Note that in some cases around unclean shutdown, it is possible the payment may have
3386         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
3387         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
3388         /// may have already been failed automatically by LDK if it was nearing its expiration time.
3389         ///
3390         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
3391         /// [`ChannelManager::claim_funds`]), you should still monitor for
3392         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
3393         /// startup during which time claims that were in-progress at shutdown may be replayed.
3394         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
3395                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3396
3397                 let removed_source = self.claimable_payments.lock().unwrap().claimable_htlcs.remove(payment_hash);
3398                 if let Some((_, mut sources)) = removed_source {
3399                         for htlc in sources.drain(..) {
3400                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
3401                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
3402                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
3403                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
3404                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
3405                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
3406                         }
3407                 }
3408         }
3409
3410         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
3411         /// that we want to return and a channel.
3412         ///
3413         /// This is for failures on the channel on which the HTLC was *received*, not failures
3414         /// forwarding
3415         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<<K::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
3416                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
3417                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
3418                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
3419                 // an inbound SCID alias before the real SCID.
3420                 let scid_pref = if chan.should_announce() {
3421                         chan.get_short_channel_id().or(chan.latest_inbound_scid_alias())
3422                 } else {
3423                         chan.latest_inbound_scid_alias().or(chan.get_short_channel_id())
3424                 };
3425                 if let Some(scid) = scid_pref {
3426                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
3427                 } else {
3428                         (0x4000|10, Vec::new())
3429                 }
3430         }
3431
3432
3433         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
3434         /// that we want to return and a channel.
3435         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<<K::Target as SignerProvider>::Signer>) -> (u16, Vec<u8>) {
3436                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
3437                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
3438                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
3439                         if desired_err_code == 0x1000 | 20 {
3440                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
3441                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
3442                                 0u16.write(&mut enc).expect("Writes cannot fail");
3443                         }
3444                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
3445                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
3446                         upd.write(&mut enc).expect("Writes cannot fail");
3447                         (desired_err_code, enc.0)
3448                 } else {
3449                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
3450                         // which means we really shouldn't have gotten a payment to be forwarded over this
3451                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
3452                         // PERM|no_such_channel should be fine.
3453                         (0x4000|10, Vec::new())
3454                 }
3455         }
3456
3457         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
3458         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
3459         // be surfaced to the user.
3460         fn fail_holding_cell_htlcs(
3461                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32],
3462                 counterparty_node_id: &PublicKey
3463         ) {
3464                 let (failure_code, onion_failure_data) =
3465                         match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
3466                                 hash_map::Entry::Occupied(chan_entry) => {
3467                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan_entry.get())
3468                                 },
3469                                 hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
3470                         };
3471
3472                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
3473                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
3474                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
3475                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
3476                 }
3477         }
3478
3479         /// Fails an HTLC backwards to the sender of it to us.
3480         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
3481         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
3482                 #[cfg(debug_assertions)]
3483                 {
3484                         // Ensure that the `channel_state` lock is not held when calling this function.
3485                         // This ensures that future code doesn't introduce a lock_order requirement for
3486                         // `forward_htlcs` to be locked after the `channel_state` lock, which calling this
3487                         // function with the `channel_state` locked would.
3488                         assert!(self.channel_state.try_lock().is_ok());
3489                 }
3490
3491                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
3492                 //identify whether we sent it or not based on the (I presume) very different runtime
3493                 //between the branches here. We should make this async and move it into the forward HTLCs
3494                 //timer handling.
3495
3496                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3497                 // from block_connected which may run during initialization prior to the chain_monitor
3498                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
3499                 match source {
3500                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, ref payment_params, .. } => {
3501                                 self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path, session_priv, payment_id, payment_params, self.probing_cookie_secret, &self.secp_ctx, &self.pending_events, &self.logger);
3502                         },
3503                         HTLCSource::PreviousHopData(HTLCPreviousHopData { ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret, ref phantom_shared_secret, ref outpoint }) => {
3504                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with {:?}", log_bytes!(payment_hash.0), onion_error);
3505                                 let err_packet = onion_error.get_encrypted_failure_packet(incoming_packet_shared_secret, phantom_shared_secret);
3506
3507                                 let mut forward_event = None;
3508                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
3509                                 if forward_htlcs.is_empty() {
3510                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
3511                                 }
3512                                 match forward_htlcs.entry(*short_channel_id) {
3513                                         hash_map::Entry::Occupied(mut entry) => {
3514                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet });
3515                                         },
3516                                         hash_map::Entry::Vacant(entry) => {
3517                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }));
3518                                         }
3519                                 }
3520                                 mem::drop(forward_htlcs);
3521                                 let mut pending_events = self.pending_events.lock().unwrap();
3522                                 if let Some(time) = forward_event {
3523                                         pending_events.push(events::Event::PendingHTLCsForwardable {
3524                                                 time_forwardable: time
3525                                         });
3526                                 }
3527                                 pending_events.push(events::Event::HTLCHandlingFailed {
3528                                         prev_channel_id: outpoint.to_channel_id(),
3529                                         failed_next_destination: destination,
3530                                 });
3531                         },
3532                 }
3533         }
3534
3535         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
3536         /// [`MessageSendEvent`]s needed to claim the payment.
3537         ///
3538         /// Note that calling this method does *not* guarantee that the payment has been claimed. You
3539         /// *must* wait for an [`Event::PaymentClaimed`] event which upon a successful claim will be
3540         /// provided to your [`EventHandler`] when [`process_pending_events`] is next called.
3541         ///
3542         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
3543         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
3544         /// event matches your expectation. If you fail to do so and call this method, you may provide
3545         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
3546         ///
3547         /// [`Event::PaymentClaimable`]: crate::util::events::Event::PaymentClaimable
3548         /// [`Event::PaymentClaimed`]: crate::util::events::Event::PaymentClaimed
3549         /// [`process_pending_events`]: EventsProvider::process_pending_events
3550         /// [`create_inbound_payment`]: Self::create_inbound_payment
3551         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
3552         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
3553                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
3554
3555                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3556
3557                 let mut sources = {
3558                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
3559                         if let Some((payment_purpose, sources)) = claimable_payments.claimable_htlcs.remove(&payment_hash) {
3560                                 let mut receiver_node_id = self.our_network_pubkey;
3561                                 for htlc in sources.iter() {
3562                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
3563                                                 let phantom_pubkey = self.keys_manager.get_node_id(Recipient::PhantomNode)
3564                                                         .expect("Failed to get node_id for phantom node recipient");
3565                                                 receiver_node_id = phantom_pubkey;
3566                                                 break;
3567                                         }
3568                                 }
3569
3570                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
3571                                         ClaimingPayment { amount_msat: sources.iter().map(|source| source.value).sum(),
3572                                         payment_purpose, receiver_node_id,
3573                                 });
3574                                 if dup_purpose.is_some() {
3575                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
3576                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
3577                                                 log_bytes!(payment_hash.0));
3578                                 }
3579                                 sources
3580                         } else { return; }
3581                 };
3582                 debug_assert!(!sources.is_empty());
3583
3584                 // If we are claiming an MPP payment, we check that all channels which contain a claimable
3585                 // HTLC still exist. While this isn't guaranteed to remain true if a channel closes while
3586                 // we're claiming (or even after we claim, before the commitment update dance completes),
3587                 // it should be a relatively rare race, and we'd rather not claim HTLCs that require us to
3588                 // go on-chain (and lose the on-chain fee to do so) than just reject the payment.
3589                 //
3590                 // Note that we'll still always get our funds - as long as the generated
3591                 // `ChannelMonitorUpdate` makes it out to the relevant monitor we can claim on-chain.
3592                 //
3593                 // If we find an HTLC which we would need to claim but for which we do not have a
3594                 // channel, we will fail all parts of the MPP payment. While we could wait and see if
3595                 // the sender retries the already-failed path(s), it should be a pretty rare case where
3596                 // we got all the HTLCs and then a channel closed while we were waiting for the user to
3597                 // provide the preimage, so worrying too much about the optimal handling isn't worth
3598                 // it.
3599                 let mut claimable_amt_msat = 0;
3600                 let mut expected_amt_msat = None;
3601                 let mut valid_mpp = true;
3602                 let mut errs = Vec::new();
3603                 let mut channel_state = Some(self.channel_state.lock().unwrap());
3604                 for htlc in sources.iter() {
3605                         let chan_id = match self.short_to_chan_info.read().unwrap().get(&htlc.prev_hop.short_channel_id) {
3606                                 Some((_cp_id, chan_id)) => chan_id.clone(),
3607                                 None => {
3608                                         valid_mpp = false;
3609                                         break;
3610                                 }
3611                         };
3612
3613                         if let None = channel_state.as_ref().unwrap().by_id.get(&chan_id) {
3614                                 valid_mpp = false;
3615                                 break;
3616                         }
3617
3618                         if expected_amt_msat.is_some() && expected_amt_msat != Some(htlc.total_msat) {
3619                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different total amounts - this should not be reachable!");
3620                                 debug_assert!(false);
3621                                 valid_mpp = false;
3622                                 break;
3623                         }
3624                         expected_amt_msat = Some(htlc.total_msat);
3625                         if let OnionPayload::Spontaneous(_) = &htlc.onion_payload {
3626                                 // We don't currently support MPP for spontaneous payments, so just check
3627                                 // that there's one payment here and move on.
3628                                 if sources.len() != 1 {
3629                                         log_error!(self.logger, "Somehow ended up with an MPP spontaneous payment - this should not be reachable!");
3630                                         debug_assert!(false);
3631                                         valid_mpp = false;
3632                                         break;
3633                                 }
3634                         }
3635
3636                         claimable_amt_msat += htlc.value;
3637                 }
3638                 if sources.is_empty() || expected_amt_msat.is_none() {
3639                         mem::drop(channel_state);
3640                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
3641                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
3642                         return;
3643                 }
3644                 if claimable_amt_msat != expected_amt_msat.unwrap() {
3645                         mem::drop(channel_state);
3646                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
3647                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
3648                                 expected_amt_msat.unwrap(), claimable_amt_msat);
3649                         return;
3650                 }
3651                 if valid_mpp {
3652                         for htlc in sources.drain(..) {
3653                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
3654                                 if let Err((pk, err)) = self.claim_funds_from_hop(channel_state.take().unwrap(), htlc.prev_hop,
3655                                         payment_preimage,
3656                                         |_| Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash }))
3657                                 {
3658                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
3659                                                 // We got a temporary failure updating monitor, but will claim the
3660                                                 // HTLC when the monitor updating is restored (or on chain).
3661                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
3662                                         } else { errs.push((pk, err)); }
3663                                 }
3664                         }
3665                 }
3666                 mem::drop(channel_state);
3667                 if !valid_mpp {
3668                         for htlc in sources.drain(..) {
3669                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
3670                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
3671                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
3672                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
3673                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
3674                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
3675                         }
3676                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
3677                 }
3678
3679                 // Now we can handle any errors which were generated.
3680                 for (counterparty_node_id, err) in errs.drain(..) {
3681                         let res: Result<(), _> = Err(err);
3682                         let _ = handle_error!(self, res, counterparty_node_id);
3683                 }
3684         }
3685
3686         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>) -> Option<MonitorUpdateCompletionAction>>(&self,
3687                 mut channel_state_lock: MutexGuard<ChannelHolder<<K::Target as SignerProvider>::Signer>>,
3688                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
3689         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
3690                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
3691
3692                 let chan_id = prev_hop.outpoint.to_channel_id();
3693                 let channel_state = &mut *channel_state_lock;
3694                 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
3695                         let counterparty_node_id = chan.get().get_counterparty_node_id();
3696                         match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
3697                                 Ok(msgs_monitor_option) => {
3698                                         if let UpdateFulfillCommitFetch::NewClaim { msgs, htlc_value_msat, monitor_update } = msgs_monitor_option {
3699                                                 match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3700                                                         ChannelMonitorUpdateStatus::Completed => {},
3701                                                         e => {
3702                                                                 log_given_level!(self.logger, if e == ChannelMonitorUpdateStatus::PermanentFailure { Level::Error } else { Level::Debug },
3703                                                                         "Failed to update channel monitor with preimage {:?}: {:?}",
3704                                                                         payment_preimage, e);
3705                                                                 let err = handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()).unwrap_err();
3706                                                                 mem::drop(channel_state_lock);
3707                                                                 self.handle_monitor_update_completion_actions(completion_action(Some(htlc_value_msat)));
3708                                                                 return Err((counterparty_node_id, err));
3709                                                         }
3710                                                 }
3711                                                 if let Some((msg, commitment_signed)) = msgs {
3712                                                         log_debug!(self.logger, "Claiming funds for HTLC with preimage {} resulted in a commitment_signed for channel {}",
3713                                                                 log_bytes!(payment_preimage.0), log_bytes!(chan.get().channel_id()));
3714                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3715                                                                 node_id: chan.get().get_counterparty_node_id(),
3716                                                                 updates: msgs::CommitmentUpdate {
3717                                                                         update_add_htlcs: Vec::new(),
3718                                                                         update_fulfill_htlcs: vec![msg],
3719                                                                         update_fail_htlcs: Vec::new(),
3720                                                                         update_fail_malformed_htlcs: Vec::new(),
3721                                                                         update_fee: None,
3722                                                                         commitment_signed,
3723                                                                 }
3724                                                         });
3725                                                 }
3726                                                 mem::drop(channel_state_lock);
3727                                                 self.handle_monitor_update_completion_actions(completion_action(Some(htlc_value_msat)));
3728                                                 Ok(())
3729                                         } else {
3730                                                 Ok(())
3731                                         }
3732                                 },
3733                                 Err((e, monitor_update)) => {
3734                                         match self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3735                                                 ChannelMonitorUpdateStatus::Completed => {},
3736                                                 e => {
3737                                                         // TODO: This needs to be handled somehow - if we receive a monitor update
3738                                                         // with a preimage we *must* somehow manage to propagate it to the upstream
3739                                                         // channel, or we must have an ability to receive the same update and try
3740                                                         // again on restart.
3741                                                         log_given_level!(self.logger, if e == ChannelMonitorUpdateStatus::PermanentFailure { Level::Error } else { Level::Info },
3742                                                                 "Failed to update channel monitor with preimage {:?} immediately prior to force-close: {:?}",
3743                                                                 payment_preimage, e);
3744                                                 },
3745                                         }
3746                                         let (drop, res) = convert_chan_err!(self, e, chan.get_mut(), &chan_id);
3747                                         if drop {
3748                                                 chan.remove_entry();
3749                                         }
3750                                         mem::drop(channel_state_lock);
3751                                         self.handle_monitor_update_completion_actions(completion_action(None));
3752                                         Err((counterparty_node_id, res))
3753                                 },
3754                         }
3755                 } else {
3756                         let preimage_update = ChannelMonitorUpdate {
3757                                 update_id: CLOSED_CHANNEL_UPDATE_ID,
3758                                 updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
3759                                         payment_preimage,
3760                                 }],
3761                         };
3762                         // We update the ChannelMonitor on the backward link, after
3763                         // receiving an `update_fulfill_htlc` from the forward link.
3764                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, preimage_update);
3765                         if update_res != ChannelMonitorUpdateStatus::Completed {
3766                                 // TODO: This needs to be handled somehow - if we receive a monitor update
3767                                 // with a preimage we *must* somehow manage to propagate it to the upstream
3768                                 // channel, or we must have an ability to receive the same event and try
3769                                 // again on restart.
3770                                 log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
3771                                         payment_preimage, update_res);
3772                         }
3773                         mem::drop(channel_state_lock);
3774                         // Note that we do process the completion action here. This totally could be a
3775                         // duplicate claim, but we have no way of knowing without interrogating the
3776                         // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
3777                         // generally always allowed to be duplicative (and it's specifically noted in
3778                         // `PaymentForwarded`).
3779                         self.handle_monitor_update_completion_actions(completion_action(None));
3780                         Ok(())
3781                 }
3782         }
3783
3784         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
3785                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
3786         }
3787
3788         fn claim_funds_internal(&self, channel_state_lock: MutexGuard<ChannelHolder<<K::Target as SignerProvider>::Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage, forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, next_channel_id: [u8; 32]) {
3789                 match source {
3790                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
3791                                 mem::drop(channel_state_lock);
3792                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage, session_priv, path, from_onchain, &self.pending_events, &self.logger);
3793                         },
3794                         HTLCSource::PreviousHopData(hop_data) => {
3795                                 let prev_outpoint = hop_data.outpoint;
3796                                 let res = self.claim_funds_from_hop(channel_state_lock, hop_data, payment_preimage,
3797                                         |htlc_claim_value_msat| {
3798                                                 if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
3799                                                         let fee_earned_msat = if let Some(claimed_htlc_value) = htlc_claim_value_msat {
3800                                                                 Some(claimed_htlc_value - forwarded_htlc_value)
3801                                                         } else { None };
3802
3803                                                         let prev_channel_id = Some(prev_outpoint.to_channel_id());
3804                                                         let next_channel_id = Some(next_channel_id);
3805
3806                                                         Some(MonitorUpdateCompletionAction::EmitEvent { event: events::Event::PaymentForwarded {
3807                                                                 fee_earned_msat,
3808                                                                 claim_from_onchain_tx: from_onchain,
3809                                                                 prev_channel_id,
3810                                                                 next_channel_id,
3811                                                         }})
3812                                                 } else { None }
3813                                         });
3814                                 if let Err((pk, err)) = res {
3815                                         let result: Result<(), _> = Err(err);
3816                                         let _ = handle_error!(self, result, pk);
3817                                 }
3818                         },
3819                 }
3820         }
3821
3822         /// Gets the node_id held by this ChannelManager
3823         pub fn get_our_node_id(&self) -> PublicKey {
3824                 self.our_network_pubkey.clone()
3825         }
3826
3827         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
3828                 for action in actions.into_iter() {
3829                         match action {
3830                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
3831                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
3832                                         if let Some(ClaimingPayment { amount_msat, payment_purpose: purpose, receiver_node_id }) = payment {
3833                                                 self.pending_events.lock().unwrap().push(events::Event::PaymentClaimed {
3834                                                         payment_hash, purpose, amount_msat, receiver_node_id: Some(receiver_node_id),
3835                                                 });
3836                                         }
3837                                 },
3838                                 MonitorUpdateCompletionAction::EmitEvent { event } => {
3839                                         self.pending_events.lock().unwrap().push(event);
3840                                 },
3841                         }
3842                 }
3843         }
3844
3845         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
3846         /// update completion.
3847         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
3848                 channel: &mut Channel<<K::Target as SignerProvider>::Signer>, raa: Option<msgs::RevokeAndACK>,
3849                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
3850                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
3851                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
3852         -> Option<(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)> {
3853                 let mut htlc_forwards = None;
3854
3855                 let counterparty_node_id = channel.get_counterparty_node_id();
3856                 if !pending_forwards.is_empty() {
3857                         htlc_forwards = Some((channel.get_short_channel_id().unwrap_or(channel.outbound_scid_alias()),
3858                                 channel.get_funding_txo().unwrap(), channel.get_user_id(), pending_forwards));
3859                 }
3860
3861                 if let Some(msg) = channel_ready {
3862                         send_channel_ready!(self, pending_msg_events, channel, msg);
3863                 }
3864                 if let Some(msg) = announcement_sigs {
3865                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3866                                 node_id: counterparty_node_id,
3867                                 msg,
3868                         });
3869                 }
3870
3871                 emit_channel_ready_event!(self, channel);
3872
3873                 macro_rules! handle_cs { () => {
3874                         if let Some(update) = commitment_update {
3875                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3876                                         node_id: counterparty_node_id,
3877                                         updates: update,
3878                                 });
3879                         }
3880                 } }
3881                 macro_rules! handle_raa { () => {
3882                         if let Some(revoke_and_ack) = raa {
3883                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
3884                                         node_id: counterparty_node_id,
3885                                         msg: revoke_and_ack,
3886                                 });
3887                         }
3888                 } }
3889                 match order {
3890                         RAACommitmentOrder::CommitmentFirst => {
3891                                 handle_cs!();
3892                                 handle_raa!();
3893                         },
3894                         RAACommitmentOrder::RevokeAndACKFirst => {
3895                                 handle_raa!();
3896                                 handle_cs!();
3897                         },
3898                 }
3899
3900                 if let Some(tx) = funding_broadcastable {
3901                         log_info!(self.logger, "Broadcasting funding transaction with txid {}", tx.txid());
3902                         self.tx_broadcaster.broadcast_transaction(&tx);
3903                 }
3904
3905                 htlc_forwards
3906         }
3907
3908         fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
3909                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3910
3911                 let htlc_forwards;
3912                 let (mut pending_failures, finalized_claims, counterparty_node_id) = {
3913                         let mut channel_lock = self.channel_state.lock().unwrap();
3914                         let channel_state = &mut *channel_lock;
3915                         let mut channel = match channel_state.by_id.entry(funding_txo.to_channel_id()) {
3916                                 hash_map::Entry::Occupied(chan) => chan,
3917                                 hash_map::Entry::Vacant(_) => return,
3918                         };
3919                         if !channel.get().is_awaiting_monitor_update() || channel.get().get_latest_monitor_update_id() != highest_applied_update_id {
3920                                 return;
3921                         }
3922
3923                         let counterparty_node_id = channel.get().get_counterparty_node_id();
3924                         let updates = channel.get_mut().monitor_updating_restored(&self.logger, self.get_our_node_id(), self.genesis_hash, self.best_block.read().unwrap().height());
3925                         let channel_update = if updates.channel_ready.is_some() && channel.get().is_usable() {
3926                                 // We only send a channel_update in the case where we are just now sending a
3927                                 // channel_ready and the channel is in a usable state. We may re-send a
3928                                 // channel_update later through the announcement_signatures process for public
3929                                 // channels, but there's no reason not to just inform our counterparty of our fees
3930                                 // now.
3931                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel.get()) {
3932                                         Some(events::MessageSendEvent::SendChannelUpdate {
3933                                                 node_id: channel.get().get_counterparty_node_id(),
3934                                                 msg,
3935                                         })
3936                                 } else { None }
3937                         } else { None };
3938                         htlc_forwards = self.handle_channel_resumption(&mut channel_state.pending_msg_events, channel.get_mut(), updates.raa, updates.commitment_update, updates.order, updates.accepted_htlcs, updates.funding_broadcastable, updates.channel_ready, updates.announcement_sigs);
3939                         if let Some(upd) = channel_update {
3940                                 channel_state.pending_msg_events.push(upd);
3941                         }
3942
3943                         (updates.failed_htlcs, updates.finalized_claimed_htlcs, counterparty_node_id)
3944                 };
3945                 if let Some(forwards) = htlc_forwards {
3946                         self.forward_htlcs(&mut [forwards][..]);
3947                 }
3948                 self.finalize_claims(finalized_claims);
3949                 for failure in pending_failures.drain(..) {
3950                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id: funding_txo.to_channel_id() };
3951                         self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
3952                 }
3953         }
3954
3955         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
3956         ///
3957         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
3958         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
3959         /// the channel.
3960         ///
3961         /// The `user_channel_id` parameter will be provided back in
3962         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
3963         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
3964         ///
3965         /// Note that this method will return an error and reject the channel, if it requires support
3966         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
3967         /// used to accept such channels.
3968         ///
3969         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
3970         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
3971         pub fn accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
3972                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
3973         }
3974
3975         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
3976         /// it as confirmed immediately.
3977         ///
3978         /// The `user_channel_id` parameter will be provided back in
3979         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
3980         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
3981         ///
3982         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
3983         /// and (if the counterparty agrees), enables forwarding of payments immediately.
3984         ///
3985         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
3986         /// transaction and blindly assumes that it will eventually confirm.
3987         ///
3988         /// If it does not confirm before we decide to close the channel, or if the funding transaction
3989         /// does not pay to the correct script the correct amount, *you will lose funds*.
3990         ///
3991         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
3992         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
3993         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> {
3994                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
3995         }
3996
3997         fn do_accept_inbound_channel(&self, temporary_channel_id: &[u8; 32], counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
3998                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
3999
4000                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4001                 let channel_state = &mut *channel_state_lock;
4002                 match channel_state.by_id.entry(temporary_channel_id.clone()) {
4003                         hash_map::Entry::Occupied(mut channel) => {
4004                                 if !channel.get().inbound_is_awaiting_accept() {
4005                                         return Err(APIError::APIMisuseError { err: "The channel isn't currently awaiting to be accepted.".to_owned() });
4006                                 }
4007                                 if *counterparty_node_id != channel.get().get_counterparty_node_id() {
4008                                         return Err(APIError::APIMisuseError { err: "The passed counterparty_node_id doesn't match the channel's counterparty node_id".to_owned() });
4009                                 }
4010                                 if accept_0conf {
4011                                         channel.get_mut().set_0conf();
4012                                 } else if channel.get().get_channel_type().requires_zero_conf() {
4013                                         let send_msg_err_event = events::MessageSendEvent::HandleError {
4014                                                 node_id: channel.get().get_counterparty_node_id(),
4015                                                 action: msgs::ErrorAction::SendErrorMessage{
4016                                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
4017                                                 }
4018                                         };
4019                                         channel_state.pending_msg_events.push(send_msg_err_event);
4020                                         let _ = remove_channel!(self, channel);
4021                                         return Err(APIError::APIMisuseError { err: "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned() });
4022                                 }
4023
4024                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4025                                         node_id: channel.get().get_counterparty_node_id(),
4026                                         msg: channel.get_mut().accept_inbound_channel(user_channel_id),
4027                                 });
4028                         }
4029                         hash_map::Entry::Vacant(_) => {
4030                                 return Err(APIError::ChannelUnavailable { err: "Can't accept a channel that doesn't exist".to_owned() });
4031                         }
4032                 }
4033                 Ok(())
4034         }
4035
4036         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
4037                 if msg.chain_hash != self.genesis_hash {
4038                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
4039                 }
4040
4041                 if !self.default_configuration.accept_inbound_channels {
4042                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
4043                 }
4044
4045                 let mut random_bytes = [0u8; 16];
4046                 random_bytes.copy_from_slice(&self.keys_manager.get_secure_random_bytes()[..16]);
4047                 let user_channel_id = u128::from_be_bytes(random_bytes);
4048
4049                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
4050                 let mut channel = match Channel::new_from_req(&self.fee_estimator, &self.keys_manager,
4051                         counterparty_node_id.clone(), &their_features, msg, user_channel_id, &self.default_configuration,
4052                         self.best_block.read().unwrap().height(), &self.logger, outbound_scid_alias)
4053                 {
4054                         Err(e) => {
4055                                 self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
4056                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
4057                         },
4058                         Ok(res) => res
4059                 };
4060                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4061                 let channel_state = &mut *channel_state_lock;
4062                 match channel_state.by_id.entry(channel.channel_id()) {
4063                         hash_map::Entry::Occupied(_) => {
4064                                 self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
4065                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone()))
4066                         },
4067                         hash_map::Entry::Vacant(entry) => {
4068                                 if !self.default_configuration.manually_accept_inbound_channels {
4069                                         if channel.get_channel_type().requires_zero_conf() {
4070                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
4071                                         }
4072                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
4073                                                 node_id: counterparty_node_id.clone(),
4074                                                 msg: channel.accept_inbound_channel(user_channel_id),
4075                                         });
4076                                 } else {
4077                                         let mut pending_events = self.pending_events.lock().unwrap();
4078                                         pending_events.push(
4079                                                 events::Event::OpenChannelRequest {
4080                                                         temporary_channel_id: msg.temporary_channel_id.clone(),
4081                                                         counterparty_node_id: counterparty_node_id.clone(),
4082                                                         funding_satoshis: msg.funding_satoshis,
4083                                                         push_msat: msg.push_msat,
4084                                                         channel_type: channel.get_channel_type().clone(),
4085                                                 }
4086                                         );
4087                                 }
4088
4089                                 entry.insert(channel);
4090                         }
4091                 }
4092                 Ok(())
4093         }
4094
4095         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
4096                 let (value, output_script, user_id) = {
4097                         let mut channel_lock = self.channel_state.lock().unwrap();
4098                         let channel_state = &mut *channel_lock;
4099                         match channel_state.by_id.entry(msg.temporary_channel_id) {
4100                                 hash_map::Entry::Occupied(mut chan) => {
4101                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4102                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
4103                                         }
4104                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &their_features), chan);
4105                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
4106                                 },
4107                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
4108                         }
4109                 };
4110                 let mut pending_events = self.pending_events.lock().unwrap();
4111                 pending_events.push(events::Event::FundingGenerationReady {
4112                         temporary_channel_id: msg.temporary_channel_id,
4113                         counterparty_node_id: *counterparty_node_id,
4114                         channel_value_satoshis: value,
4115                         output_script,
4116                         user_channel_id: user_id,
4117                 });
4118                 Ok(())
4119         }
4120
4121         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
4122                 let ((funding_msg, monitor, mut channel_ready), mut chan) = {
4123                         let best_block = *self.best_block.read().unwrap();
4124                         let mut channel_lock = self.channel_state.lock().unwrap();
4125                         let channel_state = &mut *channel_lock;
4126                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
4127                                 hash_map::Entry::Occupied(mut chan) => {
4128                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4129                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
4130                                         }
4131                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block, &self.keys_manager, &self.logger), chan), chan.remove())
4132                                 },
4133                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
4134                         }
4135                 };
4136                 // Because we have exclusive ownership of the channel here we can release the channel_state
4137                 // lock before watch_channel
4138                 match self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
4139                         ChannelMonitorUpdateStatus::Completed => {},
4140                         ChannelMonitorUpdateStatus::PermanentFailure => {
4141                                 // Note that we reply with the new channel_id in error messages if we gave up on the
4142                                 // channel, not the temporary_channel_id. This is compatible with ourselves, but the
4143                                 // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
4144                                 // any messages referencing a previously-closed channel anyway.
4145                                 // We do not propagate the monitor update to the user as it would be for a monitor
4146                                 // that we didn't manage to store (and that we don't care about - we don't respond
4147                                 // with the funding_signed so the channel can never go on chain).
4148                                 let (_monitor_update, failed_htlcs) = chan.force_shutdown(false);
4149                                 assert!(failed_htlcs.is_empty());
4150                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
4151                         },
4152                         ChannelMonitorUpdateStatus::InProgress => {
4153                                 // There's no problem signing a counterparty's funding transaction if our monitor
4154                                 // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
4155                                 // accepted payment from yet. We do, however, need to wait to send our channel_ready
4156                                 // until we have persisted our monitor.
4157                                 chan.monitor_updating_paused(false, false, channel_ready.is_some(), Vec::new(), Vec::new(), Vec::new());
4158                                 channel_ready = None; // Don't send the channel_ready now
4159                         },
4160                 }
4161                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4162                 let channel_state = &mut *channel_state_lock;
4163                 match channel_state.by_id.entry(funding_msg.channel_id) {
4164                         hash_map::Entry::Occupied(_) => {
4165                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
4166                         },
4167                         hash_map::Entry::Vacant(e) => {
4168                                 let mut id_to_peer = self.id_to_peer.lock().unwrap();
4169                                 match id_to_peer.entry(chan.channel_id()) {
4170                                         hash_map::Entry::Occupied(_) => {
4171                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(
4172                                                         "The funding_created message had the same funding_txid as an existing channel - funding is not possible".to_owned(),
4173                                                         funding_msg.channel_id))
4174                                         },
4175                                         hash_map::Entry::Vacant(i_e) => {
4176                                                 i_e.insert(chan.get_counterparty_node_id());
4177                                         }
4178                                 }
4179                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
4180                                         node_id: counterparty_node_id.clone(),
4181                                         msg: funding_msg,
4182                                 });
4183                                 if let Some(msg) = channel_ready {
4184                                         send_channel_ready!(self, channel_state.pending_msg_events, chan, msg);
4185                                 }
4186                                 e.insert(chan);
4187                         }
4188                 }
4189                 Ok(())
4190         }
4191
4192         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
4193                 let funding_tx = {
4194                         let best_block = *self.best_block.read().unwrap();
4195                         let mut channel_lock = self.channel_state.lock().unwrap();
4196                         let channel_state = &mut *channel_lock;
4197                         match channel_state.by_id.entry(msg.channel_id) {
4198                                 hash_map::Entry::Occupied(mut chan) => {
4199                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4200                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4201                                         }
4202                                         let (monitor, funding_tx, channel_ready) = match chan.get_mut().funding_signed(&msg, best_block, &self.keys_manager, &self.logger) {
4203                                                 Ok(update) => update,
4204                                                 Err(e) => try_chan_entry!(self, Err(e), chan),
4205                                         };
4206                                         match self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
4207                                                 ChannelMonitorUpdateStatus::Completed => {},
4208                                                 e => {
4209                                                         let mut res = handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::RevokeAndACKFirst, channel_ready.is_some(), OPTIONALLY_RESEND_FUNDING_LOCKED);
4210                                                         if let Err(MsgHandleErrInternal { ref mut shutdown_finish, .. }) = res {
4211                                                                 // We weren't able to watch the channel to begin with, so no updates should be made on
4212                                                                 // it. Previously, full_stack_target found an (unreachable) panic when the
4213                                                                 // monitor update contained within `shutdown_finish` was applied.
4214                                                                 if let Some((ref mut shutdown_finish, _)) = shutdown_finish {
4215                                                                         shutdown_finish.0.take();
4216                                                                 }
4217                                                         }
4218                                                         return res
4219                                                 },
4220                                         }
4221                                         if let Some(msg) = channel_ready {
4222                                                 send_channel_ready!(self, channel_state.pending_msg_events, chan.get(), msg);
4223                                         }
4224                                         funding_tx
4225                                 },
4226                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4227                         }
4228                 };
4229                 log_info!(self.logger, "Broadcasting funding transaction with txid {}", funding_tx.txid());
4230                 self.tx_broadcaster.broadcast_transaction(&funding_tx);
4231                 Ok(())
4232         }
4233
4234         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
4235                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4236                 let channel_state = &mut *channel_state_lock;
4237                 match channel_state.by_id.entry(msg.channel_id) {
4238                         hash_map::Entry::Occupied(mut chan) => {
4239                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4240                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4241                                 }
4242                                 let announcement_sigs_opt = try_chan_entry!(self, chan.get_mut().channel_ready(&msg, self.get_our_node_id(),
4243                                         self.genesis_hash.clone(), &self.best_block.read().unwrap(), &self.logger), chan);
4244                                 if let Some(announcement_sigs) = announcement_sigs_opt {
4245                                         log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(chan.get().channel_id()));
4246                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
4247                                                 node_id: counterparty_node_id.clone(),
4248                                                 msg: announcement_sigs,
4249                                         });
4250                                 } else if chan.get().is_usable() {
4251                                         // If we're sending an announcement_signatures, we'll send the (public)
4252                                         // channel_update after sending a channel_announcement when we receive our
4253                                         // counterparty's announcement_signatures. Thus, we only bother to send a
4254                                         // channel_update here if the channel is not public, i.e. we're not sending an
4255                                         // announcement_signatures.
4256                                         log_trace!(self.logger, "Sending private initial channel_update for our counterparty on channel {}", log_bytes!(chan.get().channel_id()));
4257                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
4258                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4259                                                         node_id: counterparty_node_id.clone(),
4260                                                         msg,
4261                                                 });
4262                                         }
4263                                 }
4264
4265                                 emit_channel_ready_event!(self, chan.get_mut());
4266
4267                                 Ok(())
4268                         },
4269                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4270                 }
4271         }
4272
4273         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
4274                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)>;
4275                 let result: Result<(), _> = loop {
4276                         let mut channel_state_lock = self.channel_state.lock().unwrap();
4277                         let channel_state = &mut *channel_state_lock;
4278
4279                         match channel_state.by_id.entry(msg.channel_id.clone()) {
4280                                 hash_map::Entry::Occupied(mut chan_entry) => {
4281                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
4282                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4283                                         }
4284
4285                                         if !chan_entry.get().received_shutdown() {
4286                                                 log_info!(self.logger, "Received a shutdown message from our counterparty for channel {}{}.",
4287                                                         log_bytes!(msg.channel_id),
4288                                                         if chan_entry.get().sent_shutdown() { " after we initiated shutdown" } else { "" });
4289                                         }
4290
4291                                         let (shutdown, monitor_update, htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.keys_manager, &their_features, &msg), chan_entry);
4292                                         dropped_htlcs = htlcs;
4293
4294                                         // Update the monitor with the shutdown script if necessary.
4295                                         if let Some(monitor_update) = monitor_update {
4296                                                 let update_res = self.chain_monitor.update_channel(chan_entry.get().get_funding_txo().unwrap(), monitor_update);
4297                                                 let (result, is_permanent) =
4298                                                         handle_monitor_update_res!(self, update_res, chan_entry.get_mut(), RAACommitmentOrder::CommitmentFirst, chan_entry.key(), NO_UPDATE);
4299                                                 if is_permanent {
4300                                                         remove_channel!(self, chan_entry);
4301                                                         break result;
4302                                                 }
4303                                         }
4304
4305                                         if let Some(msg) = shutdown {
4306                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
4307                                                         node_id: *counterparty_node_id,
4308                                                         msg,
4309                                                 });
4310                                         }
4311
4312                                         break Ok(());
4313                                 },
4314                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4315                         }
4316                 };
4317                 for htlc_source in dropped_htlcs.drain(..) {
4318                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
4319                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
4320                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
4321                 }
4322
4323                 let _ = handle_error!(self, result, *counterparty_node_id);
4324                 Ok(())
4325         }
4326
4327         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
4328                 let (tx, chan_option) = {
4329                         let mut channel_state_lock = self.channel_state.lock().unwrap();
4330                         let channel_state = &mut *channel_state_lock;
4331                         match channel_state.by_id.entry(msg.channel_id.clone()) {
4332                                 hash_map::Entry::Occupied(mut chan_entry) => {
4333                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
4334                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4335                                         }
4336                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), chan_entry);
4337                                         if let Some(msg) = closing_signed {
4338                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
4339                                                         node_id: counterparty_node_id.clone(),
4340                                                         msg,
4341                                                 });
4342                                         }
4343                                         if tx.is_some() {
4344                                                 // We're done with this channel, we've got a signed closing transaction and
4345                                                 // will send the closing_signed back to the remote peer upon return. This
4346                                                 // also implies there are no pending HTLCs left on the channel, so we can
4347                                                 // fully delete it from tracking (the channel monitor is still around to
4348                                                 // watch for old state broadcasts)!
4349                                                 (tx, Some(remove_channel!(self, chan_entry)))
4350                                         } else { (tx, None) }
4351                                 },
4352                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4353                         }
4354                 };
4355                 if let Some(broadcast_tx) = tx {
4356                         log_info!(self.logger, "Broadcasting {}", log_tx!(broadcast_tx));
4357                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
4358                 }
4359                 if let Some(chan) = chan_option {
4360                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4361                                 let mut channel_state = self.channel_state.lock().unwrap();
4362                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4363                                         msg: update
4364                                 });
4365                         }
4366                         self.issue_channel_close_events(&chan, ClosureReason::CooperativeClosure);
4367                 }
4368                 Ok(())
4369         }
4370
4371         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
4372                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
4373                 //determine the state of the payment based on our response/if we forward anything/the time
4374                 //we take to respond. We should take care to avoid allowing such an attack.
4375                 //
4376                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
4377                 //us repeatedly garbled in different ways, and compare our error messages, which are
4378                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
4379                 //but we should prevent it anyway.
4380
4381                 let pending_forward_info = self.decode_update_add_htlc_onion(msg);
4382                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4383                 let channel_state = &mut *channel_state_lock;
4384
4385                 match channel_state.by_id.entry(msg.channel_id) {
4386                         hash_map::Entry::Occupied(mut chan) => {
4387                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4388                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4389                                 }
4390
4391                                 let create_pending_htlc_status = |chan: &Channel<<K::Target as SignerProvider>::Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
4392                                         // If the update_add is completely bogus, the call will Err and we will close,
4393                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
4394                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
4395                                         match pending_forward_info {
4396                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
4397                                                         let reason = if (error_code & 0x1000) != 0 {
4398                                                                 let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
4399                                                                 HTLCFailReason::reason(real_code, error_data)
4400                                                         } else {
4401                                                                 HTLCFailReason::from_failure_code(error_code)
4402                                                         }.get_encrypted_failure_packet(incoming_shared_secret, &None);
4403                                                         let msg = msgs::UpdateFailHTLC {
4404                                                                 channel_id: msg.channel_id,
4405                                                                 htlc_id: msg.htlc_id,
4406                                                                 reason
4407                                                         };
4408                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
4409                                                 },
4410                                                 _ => pending_forward_info
4411                                         }
4412                                 };
4413                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), chan);
4414                         },
4415                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4416                 }
4417                 Ok(())
4418         }
4419
4420         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
4421                 let mut channel_lock = self.channel_state.lock().unwrap();
4422                 let (htlc_source, forwarded_htlc_value) = {
4423                         let channel_state = &mut *channel_lock;
4424                         match channel_state.by_id.entry(msg.channel_id) {
4425                                 hash_map::Entry::Occupied(mut chan) => {
4426                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4427                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4428                                         }
4429                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), chan)
4430                                 },
4431                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4432                         }
4433                 };
4434                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value), false, msg.channel_id);
4435                 Ok(())
4436         }
4437
4438         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
4439                 let mut channel_lock = self.channel_state.lock().unwrap();
4440                 let channel_state = &mut *channel_lock;
4441                 match channel_state.by_id.entry(msg.channel_id) {
4442                         hash_map::Entry::Occupied(mut chan) => {
4443                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4444                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4445                                 }
4446                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan);
4447                         },
4448                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4449                 }
4450                 Ok(())
4451         }
4452
4453         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
4454                 let mut channel_lock = self.channel_state.lock().unwrap();
4455                 let channel_state = &mut *channel_lock;
4456                 match channel_state.by_id.entry(msg.channel_id) {
4457                         hash_map::Entry::Occupied(mut chan) => {
4458                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4459                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4460                                 }
4461                                 if (msg.failure_code & 0x8000) == 0 {
4462                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
4463                                         try_chan_entry!(self, Err(chan_err), chan);
4464                                 }
4465                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan);
4466                                 Ok(())
4467                         },
4468                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4469                 }
4470         }
4471
4472         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
4473                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4474                 let channel_state = &mut *channel_state_lock;
4475                 match channel_state.by_id.entry(msg.channel_id) {
4476                         hash_map::Entry::Occupied(mut chan) => {
4477                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4478                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4479                                 }
4480                                 let (revoke_and_ack, commitment_signed, monitor_update) =
4481                                         match chan.get_mut().commitment_signed(&msg, &self.logger) {
4482                                                 Err((None, e)) => try_chan_entry!(self, Err(e), chan),
4483                                                 Err((Some(update), e)) => {
4484                                                         assert!(chan.get().is_awaiting_monitor_update());
4485                                                         let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update);
4486                                                         try_chan_entry!(self, Err(e), chan);
4487                                                         unreachable!();
4488                                                 },
4489                                                 Ok(res) => res
4490                                         };
4491                                 let update_res = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update);
4492                                 if let Err(e) = handle_monitor_update_res!(self, update_res, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some()) {
4493                                         return Err(e);
4494                                 }
4495
4496                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
4497                                         node_id: counterparty_node_id.clone(),
4498                                         msg: revoke_and_ack,
4499                                 });
4500                                 if let Some(msg) = commitment_signed {
4501                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4502                                                 node_id: counterparty_node_id.clone(),
4503                                                 updates: msgs::CommitmentUpdate {
4504                                                         update_add_htlcs: Vec::new(),
4505                                                         update_fulfill_htlcs: Vec::new(),
4506                                                         update_fail_htlcs: Vec::new(),
4507                                                         update_fail_malformed_htlcs: Vec::new(),
4508                                                         update_fee: None,
4509                                                         commitment_signed: msg,
4510                                                 },
4511                                         });
4512                                 }
4513                                 Ok(())
4514                         },
4515                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4516                 }
4517         }
4518
4519         #[inline]
4520         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, u128, Vec<(PendingHTLCInfo, u64)>)]) {
4521                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
4522                         let mut forward_event = None;
4523                         let mut new_intercept_events = Vec::new();
4524                         let mut failed_intercept_forwards = Vec::new();
4525                         if !pending_forwards.is_empty() {
4526                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
4527                                         let scid = match forward_info.routing {
4528                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
4529                                                 PendingHTLCRouting::Receive { .. } => 0,
4530                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
4531                                         };
4532                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
4533                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
4534
4535                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
4536                                         let forward_htlcs_empty = forward_htlcs.is_empty();
4537                                         match forward_htlcs.entry(scid) {
4538                                                 hash_map::Entry::Occupied(mut entry) => {
4539                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4540                                                                 prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info }));
4541                                                 },
4542                                                 hash_map::Entry::Vacant(entry) => {
4543                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
4544                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.genesis_hash)
4545                                                         {
4546                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
4547                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
4548                                                                 match pending_intercepts.entry(intercept_id) {
4549                                                                         hash_map::Entry::Vacant(entry) => {
4550                                                                                 new_intercept_events.push(events::Event::HTLCIntercepted {
4551                                                                                         requested_next_hop_scid: scid,
4552                                                                                         payment_hash: forward_info.payment_hash,
4553                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
4554                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
4555                                                                                         intercept_id
4556                                                                                 });
4557                                                                                 entry.insert(PendingAddHTLCInfo {
4558                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info });
4559                                                                         },
4560                                                                         hash_map::Entry::Occupied(_) => {
4561                                                                                 log_info!(self.logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
4562                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4563                                                                                         short_channel_id: prev_short_channel_id,
4564                                                                                         outpoint: prev_funding_outpoint,
4565                                                                                         htlc_id: prev_htlc_id,
4566                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
4567                                                                                         phantom_shared_secret: None,
4568                                                                                 });
4569
4570                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
4571                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
4572                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
4573                                                                                 ));
4574                                                                         }
4575                                                                 }
4576                                                         } else {
4577                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
4578                                                                 // payments are being processed.
4579                                                                 if forward_htlcs_empty {
4580                                                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
4581                                                                 }
4582                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4583                                                                         prev_short_channel_id, prev_funding_outpoint, prev_htlc_id, prev_user_channel_id, forward_info })));
4584                                                         }
4585                                                 }
4586                                         }
4587                                 }
4588                         }
4589
4590                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
4591                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4592                         }
4593
4594                         if !new_intercept_events.is_empty() {
4595                                 let mut events = self.pending_events.lock().unwrap();
4596                                 events.append(&mut new_intercept_events);
4597                         }
4598
4599                         match forward_event {
4600                                 Some(time) => {
4601                                         let mut pending_events = self.pending_events.lock().unwrap();
4602                                         pending_events.push(events::Event::PendingHTLCsForwardable {
4603                                                 time_forwardable: time
4604                                         });
4605                                 }
4606                                 None => {},
4607                         }
4608                 }
4609         }
4610
4611         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
4612                 let mut htlcs_to_fail = Vec::new();
4613                 let res = loop {
4614                         let mut channel_state_lock = self.channel_state.lock().unwrap();
4615                         let channel_state = &mut *channel_state_lock;
4616                         match channel_state.by_id.entry(msg.channel_id) {
4617                                 hash_map::Entry::Occupied(mut chan) => {
4618                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4619                                                 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4620                                         }
4621                                         let was_paused_for_mon_update = chan.get().is_awaiting_monitor_update();
4622                                         let raa_updates = break_chan_entry!(self,
4623                                                 chan.get_mut().revoke_and_ack(&msg, &self.logger), chan);
4624                                         htlcs_to_fail = raa_updates.holding_cell_failed_htlcs;
4625                                         let update_res = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), raa_updates.monitor_update);
4626                                         if was_paused_for_mon_update {
4627                                                 assert!(update_res != ChannelMonitorUpdateStatus::Completed);
4628                                                 assert!(raa_updates.commitment_update.is_none());
4629                                                 assert!(raa_updates.accepted_htlcs.is_empty());
4630                                                 assert!(raa_updates.failed_htlcs.is_empty());
4631                                                 assert!(raa_updates.finalized_claimed_htlcs.is_empty());
4632                                                 break Err(MsgHandleErrInternal::ignore_no_close("Existing pending monitor update prevented responses to RAA".to_owned()));
4633                                         }
4634                                         if update_res != ChannelMonitorUpdateStatus::Completed {
4635                                                 if let Err(e) = handle_monitor_update_res!(self, update_res, chan,
4636                                                                 RAACommitmentOrder::CommitmentFirst, false,
4637                                                                 raa_updates.commitment_update.is_some(), false,
4638                                                                 raa_updates.accepted_htlcs, raa_updates.failed_htlcs,
4639                                                                 raa_updates.finalized_claimed_htlcs) {
4640                                                         break Err(e);
4641                                                 } else { unreachable!(); }
4642                                         }
4643                                         if let Some(updates) = raa_updates.commitment_update {
4644                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4645                                                         node_id: counterparty_node_id.clone(),
4646                                                         updates,
4647                                                 });
4648                                         }
4649                                         break Ok((raa_updates.accepted_htlcs, raa_updates.failed_htlcs,
4650                                                         raa_updates.finalized_claimed_htlcs,
4651                                                         chan.get().get_short_channel_id()
4652                                                                 .unwrap_or(chan.get().outbound_scid_alias()),
4653                                                         chan.get().get_funding_txo().unwrap(),
4654                                                         chan.get().get_user_id()))
4655                                 },
4656                                 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4657                         }
4658                 };
4659                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
4660                 match res {
4661                         Ok((pending_forwards, mut pending_failures, finalized_claim_htlcs,
4662                                 short_channel_id, channel_outpoint, user_channel_id)) =>
4663                         {
4664                                 for failure in pending_failures.drain(..) {
4665                                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: channel_outpoint.to_channel_id() };
4666                                         self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
4667                                 }
4668                                 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, user_channel_id, pending_forwards)]);
4669                                 self.finalize_claims(finalized_claim_htlcs);
4670                                 Ok(())
4671                         },
4672                         Err(e) => Err(e)
4673                 }
4674         }
4675
4676         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
4677                 let mut channel_lock = self.channel_state.lock().unwrap();
4678                 let channel_state = &mut *channel_lock;
4679                 match channel_state.by_id.entry(msg.channel_id) {
4680                         hash_map::Entry::Occupied(mut chan) => {
4681                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4682                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4683                                 }
4684                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg, &self.logger), chan);
4685                         },
4686                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4687                 }
4688                 Ok(())
4689         }
4690
4691         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
4692                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4693                 let channel_state = &mut *channel_state_lock;
4694
4695                 match channel_state.by_id.entry(msg.channel_id) {
4696                         hash_map::Entry::Occupied(mut chan) => {
4697                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4698                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4699                                 }
4700                                 if !chan.get().is_usable() {
4701                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
4702                                 }
4703
4704                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
4705                                         msg: try_chan_entry!(self, chan.get_mut().announcement_signatures(
4706                                                 self.get_our_node_id(), self.genesis_hash.clone(), self.best_block.read().unwrap().height(), msg), chan),
4707                                         // Note that announcement_signatures fails if the channel cannot be announced,
4708                                         // so get_channel_update_for_broadcast will never fail by the time we get here.
4709                                         update_msg: self.get_channel_update_for_broadcast(chan.get()).unwrap(),
4710                                 });
4711                         },
4712                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4713                 }
4714                 Ok(())
4715         }
4716
4717         /// Returns ShouldPersist if anything changed, otherwise either SkipPersist or an Err.
4718         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
4719                 let chan_id = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
4720                         Some((_cp_id, chan_id)) => chan_id.clone(),
4721                         None => {
4722                                 // It's not a local channel
4723                                 return Ok(NotifyOption::SkipPersist)
4724                         }
4725                 };
4726                 let mut channel_state_lock = self.channel_state.lock().unwrap();
4727                 let channel_state = &mut *channel_state_lock;
4728                 match channel_state.by_id.entry(chan_id) {
4729                         hash_map::Entry::Occupied(mut chan) => {
4730                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4731                                         if chan.get().should_announce() {
4732                                                 // If the announcement is about a channel of ours which is public, some
4733                                                 // other peer may simply be forwarding all its gossip to us. Don't provide
4734                                                 // a scary-looking error message and return Ok instead.
4735                                                 return Ok(NotifyOption::SkipPersist);
4736                                         }
4737                                         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));
4738                                 }
4739                                 let were_node_one = self.get_our_node_id().serialize()[..] < chan.get().get_counterparty_node_id().serialize()[..];
4740                                 let msg_from_node_one = msg.contents.flags & 1 == 0;
4741                                 if were_node_one == msg_from_node_one {
4742                                         return Ok(NotifyOption::SkipPersist);
4743                                 } else {
4744                                         log_debug!(self.logger, "Received channel_update for channel {}.", log_bytes!(chan_id));
4745                                         try_chan_entry!(self, chan.get_mut().channel_update(&msg), chan);
4746                                 }
4747                         },
4748                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersist)
4749                 }
4750                 Ok(NotifyOption::DoPersist)
4751         }
4752
4753         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
4754                 let htlc_forwards;
4755                 let need_lnd_workaround = {
4756                         let mut channel_state_lock = self.channel_state.lock().unwrap();
4757                         let channel_state = &mut *channel_state_lock;
4758
4759                         match channel_state.by_id.entry(msg.channel_id) {
4760                                 hash_map::Entry::Occupied(mut chan) => {
4761                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
4762                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
4763                                         }
4764                                         // Currently, we expect all holding cell update_adds to be dropped on peer
4765                                         // disconnect, so Channel's reestablish will never hand us any holding cell
4766                                         // freed HTLCs to fail backwards. If in the future we no longer drop pending
4767                                         // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
4768                                         let responses = try_chan_entry!(self, chan.get_mut().channel_reestablish(
4769                                                 msg, &self.logger, self.our_network_pubkey.clone(), self.genesis_hash,
4770                                                 &*self.best_block.read().unwrap()), chan);
4771                                         let mut channel_update = None;
4772                                         if let Some(msg) = responses.shutdown_msg {
4773                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
4774                                                         node_id: counterparty_node_id.clone(),
4775                                                         msg,
4776                                                 });
4777                                         } else if chan.get().is_usable() {
4778                                                 // If the channel is in a usable state (ie the channel is not being shut
4779                                                 // down), send a unicast channel_update to our counterparty to make sure
4780                                                 // they have the latest channel parameters.
4781                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan.get()) {
4782                                                         channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
4783                                                                 node_id: chan.get().get_counterparty_node_id(),
4784                                                                 msg,
4785                                                         });
4786                                                 }
4787                                         }
4788                                         let need_lnd_workaround = chan.get_mut().workaround_lnd_bug_4006.take();
4789                                         htlc_forwards = self.handle_channel_resumption(
4790                                                 &mut channel_state.pending_msg_events, chan.get_mut(), responses.raa, responses.commitment_update, responses.order,
4791                                                 Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
4792                                         if let Some(upd) = channel_update {
4793                                                 channel_state.pending_msg_events.push(upd);
4794                                         }
4795                                         need_lnd_workaround
4796                                 },
4797                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
4798                         }
4799                 };
4800
4801                 if let Some(forwards) = htlc_forwards {
4802                         self.forward_htlcs(&mut [forwards][..]);
4803                 }
4804
4805                 if let Some(channel_ready_msg) = need_lnd_workaround {
4806                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
4807                 }
4808                 Ok(())
4809         }
4810
4811         /// Process pending events from the `chain::Watch`, returning whether any events were processed.
4812         fn process_pending_monitor_events(&self) -> bool {
4813                 let mut failed_channels = Vec::new();
4814                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
4815                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
4816                 for (funding_outpoint, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
4817                         for monitor_event in monitor_events.drain(..) {
4818                                 match monitor_event {
4819                                         MonitorEvent::HTLCEvent(htlc_update) => {
4820                                                 if let Some(preimage) = htlc_update.payment_preimage {
4821                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
4822                                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, funding_outpoint.to_channel_id());
4823                                                 } else {
4824                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
4825                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id: funding_outpoint.to_channel_id() };
4826                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
4827                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
4828                                                 }
4829                                         },
4830                                         MonitorEvent::CommitmentTxConfirmed(funding_outpoint) |
4831                                         MonitorEvent::UpdateFailed(funding_outpoint) => {
4832                                                 let mut channel_lock = self.channel_state.lock().unwrap();
4833                                                 let channel_state = &mut *channel_lock;
4834                                                 let by_id = &mut channel_state.by_id;
4835                                                 let pending_msg_events = &mut channel_state.pending_msg_events;
4836                                                 if let hash_map::Entry::Occupied(chan_entry) = by_id.entry(funding_outpoint.to_channel_id()) {
4837                                                         let mut chan = remove_channel!(self, chan_entry);
4838                                                         failed_channels.push(chan.force_shutdown(false));
4839                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4840                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4841                                                                         msg: update
4842                                                                 });
4843                                                         }
4844                                                         let reason = if let MonitorEvent::UpdateFailed(_) = monitor_event {
4845                                                                 ClosureReason::ProcessingError { err: "Failed to persist ChannelMonitor update during chain sync".to_string() }
4846                                                         } else {
4847                                                                 ClosureReason::CommitmentTxConfirmed
4848                                                         };
4849                                                         self.issue_channel_close_events(&chan, reason);
4850                                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
4851                                                                 node_id: chan.get_counterparty_node_id(),
4852                                                                 action: msgs::ErrorAction::SendErrorMessage {
4853                                                                         msg: msgs::ErrorMessage { channel_id: chan.channel_id(), data: "Channel force-closed".to_owned() }
4854                                                                 },
4855                                                         });
4856                                                 }
4857                                         },
4858                                         MonitorEvent::Completed { funding_txo, monitor_update_id } => {
4859                                                 self.channel_monitor_updated(&funding_txo, monitor_update_id);
4860                                         },
4861                                 }
4862                         }
4863                 }
4864
4865                 for failure in failed_channels.drain(..) {
4866                         self.finish_force_close_channel(failure);
4867                 }
4868
4869                 has_pending_monitor_events
4870         }
4871
4872         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
4873         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
4874         /// update events as a separate process method here.
4875         #[cfg(fuzzing)]
4876         pub fn process_monitor_events(&self) {
4877                 self.process_pending_monitor_events();
4878         }
4879
4880         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
4881         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
4882         /// update was applied.
4883         fn check_free_holding_cells(&self) -> bool {
4884                 let mut has_monitor_update = false;
4885                 let mut failed_htlcs = Vec::new();
4886                 let mut handle_errors = Vec::new();
4887                 {
4888                         let mut channel_state_lock = self.channel_state.lock().unwrap();
4889                         let channel_state = &mut *channel_state_lock;
4890                         let by_id = &mut channel_state.by_id;
4891                         let pending_msg_events = &mut channel_state.pending_msg_events;
4892
4893                         by_id.retain(|channel_id, chan| {
4894                                 match chan.maybe_free_holding_cell_htlcs(&self.logger) {
4895                                         Ok((commitment_opt, holding_cell_failed_htlcs)) => {
4896                                                 if !holding_cell_failed_htlcs.is_empty() {
4897                                                         failed_htlcs.push((
4898                                                                 holding_cell_failed_htlcs,
4899                                                                 *channel_id,
4900                                                                 chan.get_counterparty_node_id()
4901                                                         ));
4902                                                 }
4903                                                 if let Some((commitment_update, monitor_update)) = commitment_opt {
4904                                                         match self.chain_monitor.update_channel(chan.get_funding_txo().unwrap(), monitor_update) {
4905                                                                 ChannelMonitorUpdateStatus::Completed => {
4906                                                                         pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
4907                                                                                 node_id: chan.get_counterparty_node_id(),
4908                                                                                 updates: commitment_update,
4909                                                                         });
4910                                                                 },
4911                                                                 e => {
4912                                                                         has_monitor_update = true;
4913                                                                         let (res, close_channel) = handle_monitor_update_res!(self, e, chan, RAACommitmentOrder::CommitmentFirst, channel_id, COMMITMENT_UPDATE_ONLY);
4914                                                                         handle_errors.push((chan.get_counterparty_node_id(), res));
4915                                                                         if close_channel { return false; }
4916                                                                 },
4917                                                         }
4918                                                 }
4919                                                 true
4920                                         },
4921                                         Err(e) => {
4922                                                 let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
4923                                                 handle_errors.push((chan.get_counterparty_node_id(), Err(res)));
4924                                                 // ChannelClosed event is generated by handle_error for us
4925                                                 !close_channel
4926                                         }
4927                                 }
4928                         });
4929                 }
4930
4931                 let has_update = has_monitor_update || !failed_htlcs.is_empty() || !handle_errors.is_empty();
4932                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
4933                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
4934                 }
4935
4936                 for (counterparty_node_id, err) in handle_errors.drain(..) {
4937                         let _ = handle_error!(self, err, counterparty_node_id);
4938                 }
4939
4940                 has_update
4941         }
4942
4943         /// Check whether any channels have finished removing all pending updates after a shutdown
4944         /// exchange and can now send a closing_signed.
4945         /// Returns whether any closing_signed messages were generated.
4946         fn maybe_generate_initial_closing_signed(&self) -> bool {
4947                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
4948                 let mut has_update = false;
4949                 {
4950                         let mut channel_state_lock = self.channel_state.lock().unwrap();
4951                         let channel_state = &mut *channel_state_lock;
4952                         let by_id = &mut channel_state.by_id;
4953                         let pending_msg_events = &mut channel_state.pending_msg_events;
4954
4955                         by_id.retain(|channel_id, chan| {
4956                                 match chan.maybe_propose_closing_signed(&self.fee_estimator, &self.logger) {
4957                                         Ok((msg_opt, tx_opt)) => {
4958                                                 if let Some(msg) = msg_opt {
4959                                                         has_update = true;
4960                                                         pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
4961                                                                 node_id: chan.get_counterparty_node_id(), msg,
4962                                                         });
4963                                                 }
4964                                                 if let Some(tx) = tx_opt {
4965                                                         // We're done with this channel. We got a closing_signed and sent back
4966                                                         // a closing_signed with a closing transaction to broadcast.
4967                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4968                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
4969                                                                         msg: update
4970                                                                 });
4971                                                         }
4972
4973                                                         self.issue_channel_close_events(chan, ClosureReason::CooperativeClosure);
4974
4975                                                         log_info!(self.logger, "Broadcasting {}", log_tx!(tx));
4976                                                         self.tx_broadcaster.broadcast_transaction(&tx);
4977                                                         update_maps_on_chan_removal!(self, chan);
4978                                                         false
4979                                                 } else { true }
4980                                         },
4981                                         Err(e) => {
4982                                                 has_update = true;
4983                                                 let (close_channel, res) = convert_chan_err!(self, e, chan, channel_id);
4984                                                 handle_errors.push((chan.get_counterparty_node_id(), Err(res)));
4985                                                 !close_channel
4986                                         }
4987                                 }
4988                         });
4989                 }
4990
4991                 for (counterparty_node_id, err) in handle_errors.drain(..) {
4992                         let _ = handle_error!(self, err, counterparty_node_id);
4993                 }
4994
4995                 has_update
4996         }
4997
4998         /// Handle a list of channel failures during a block_connected or block_disconnected call,
4999         /// pushing the channel monitor update (if any) to the background events queue and removing the
5000         /// Channel object.
5001         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
5002                 for mut failure in failed_channels.drain(..) {
5003                         // Either a commitment transactions has been confirmed on-chain or
5004                         // Channel::block_disconnected detected that the funding transaction has been
5005                         // reorganized out of the main chain.
5006                         // We cannot broadcast our latest local state via monitor update (as
5007                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
5008                         // so we track the update internally and handle it when the user next calls
5009                         // timer_tick_occurred, guaranteeing we're running normally.
5010                         if let Some((funding_txo, update)) = failure.0.take() {
5011                                 assert_eq!(update.updates.len(), 1);
5012                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
5013                                         assert!(should_broadcast);
5014                                 } else { unreachable!(); }
5015                                 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
5016                         }
5017                         self.finish_force_close_channel(failure);
5018                 }
5019         }
5020
5021         fn set_payment_hash_secret_map(&self, payment_hash: PaymentHash, payment_preimage: Option<PaymentPreimage>, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, APIError> {
5022                 assert!(invoice_expiry_delta_secs <= 60*60*24*365); // Sadly bitcoin timestamps are u32s, so panic before 2106
5023
5024                 if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
5025                         return Err(APIError::APIMisuseError { err: format!("min_value_msat of {} greater than total 21 million bitcoin supply", min_value_msat.unwrap()) });
5026                 }
5027
5028                 let payment_secret = PaymentSecret(self.keys_manager.get_secure_random_bytes());
5029
5030                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5031                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
5032                 match payment_secrets.entry(payment_hash) {
5033                         hash_map::Entry::Vacant(e) => {
5034                                 e.insert(PendingInboundPayment {
5035                                         payment_secret, min_value_msat, payment_preimage,
5036                                         user_payment_id: 0, // For compatibility with version 0.0.103 and earlier
5037                                         // We assume that highest_seen_timestamp is pretty close to the current time -
5038                                         // it's updated when we receive a new block with the maximum time we've seen in
5039                                         // a header. It should never be more than two hours in the future.
5040                                         // Thus, we add two hours here as a buffer to ensure we absolutely
5041                                         // never fail a payment too early.
5042                                         // Note that we assume that received blocks have reasonably up-to-date
5043                                         // timestamps.
5044                                         expiry_time: self.highest_seen_timestamp.load(Ordering::Acquire) as u64 + invoice_expiry_delta_secs as u64 + 7200,
5045                                 });
5046                         },
5047                         hash_map::Entry::Occupied(_) => return Err(APIError::APIMisuseError { err: "Duplicate payment hash".to_owned() }),
5048                 }
5049                 Ok(payment_secret)
5050         }
5051
5052         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
5053         /// to pay us.
5054         ///
5055         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
5056         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
5057         ///
5058         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
5059         /// will have the [`PaymentClaimable::payment_preimage`] field filled in. That should then be
5060         /// passed directly to [`claim_funds`].
5061         ///
5062         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
5063         ///
5064         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
5065         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
5066         ///
5067         /// # Note
5068         ///
5069         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
5070         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
5071         ///
5072         /// Errors if `min_value_msat` is greater than total bitcoin supply.
5073         ///
5074         /// [`claim_funds`]: Self::claim_funds
5075         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
5076         /// [`PaymentClaimable::payment_preimage`]: events::Event::PaymentClaimable::payment_preimage
5077         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5078         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<(PaymentHash, PaymentSecret), ()> {
5079                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs, &self.keys_manager, self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
5080         }
5081
5082         /// Legacy version of [`create_inbound_payment`]. Use this method if you wish to share
5083         /// serialized state with LDK node(s) running 0.0.103 and earlier.
5084         ///
5085         /// May panic if `invoice_expiry_delta_secs` is greater than one year.
5086         ///
5087         /// # Note
5088         /// This method is deprecated and will be removed soon.
5089         ///
5090         /// [`create_inbound_payment`]: Self::create_inbound_payment
5091         #[deprecated]
5092         pub fn create_inbound_payment_legacy(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<(PaymentHash, PaymentSecret), APIError> {
5093                 let payment_preimage = PaymentPreimage(self.keys_manager.get_secure_random_bytes());
5094                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
5095                 let payment_secret = self.set_payment_hash_secret_map(payment_hash, Some(payment_preimage), min_value_msat, invoice_expiry_delta_secs)?;
5096                 Ok((payment_hash, payment_secret))
5097         }
5098
5099         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
5100         /// stored external to LDK.
5101         ///
5102         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
5103         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
5104         /// the `min_value_msat` provided here, if one is provided.
5105         ///
5106         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
5107         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
5108         /// payments.
5109         ///
5110         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
5111         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
5112         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
5113         /// sender "proof-of-payment" unless they have paid the required amount.
5114         ///
5115         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
5116         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
5117         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
5118         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
5119         /// invoices when no timeout is set.
5120         ///
5121         /// Note that we use block header time to time-out pending inbound payments (with some margin
5122         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
5123         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
5124         /// If you need exact expiry semantics, you should enforce them upon receipt of
5125         /// [`PaymentClaimable`].
5126         ///
5127         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry`
5128         /// set to at least [`MIN_FINAL_CLTV_EXPIRY`].
5129         ///
5130         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
5131         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
5132         ///
5133         /// # Note
5134         ///
5135         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
5136         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
5137         ///
5138         /// Errors if `min_value_msat` is greater than total bitcoin supply.
5139         ///
5140         /// [`create_inbound_payment`]: Self::create_inbound_payment
5141         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
5142         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, ()> {
5143                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash, invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
5144         }
5145
5146         /// Legacy version of [`create_inbound_payment_for_hash`]. Use this method if you wish to share
5147         /// serialized state with LDK node(s) running 0.0.103 and earlier.
5148         ///
5149         /// May panic if `invoice_expiry_delta_secs` is greater than one year.
5150         ///
5151         /// # Note
5152         /// This method is deprecated and will be removed soon.
5153         ///
5154         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5155         #[deprecated]
5156         pub fn create_inbound_payment_for_hash_legacy(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32) -> Result<PaymentSecret, APIError> {
5157                 self.set_payment_hash_secret_map(payment_hash, None, min_value_msat, invoice_expiry_delta_secs)
5158         }
5159
5160         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
5161         /// previously returned from [`create_inbound_payment`].
5162         ///
5163         /// [`create_inbound_payment`]: Self::create_inbound_payment
5164         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
5165                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
5166         }
5167
5168         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
5169         /// are used when constructing the phantom invoice's route hints.
5170         ///
5171         /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
5172         pub fn get_phantom_scid(&self) -> u64 {
5173                 let best_block_height = self.best_block.read().unwrap().height();
5174                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
5175                 loop {
5176                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.keys_manager);
5177                         // Ensure the generated scid doesn't conflict with a real channel.
5178                         match short_to_chan_info.get(&scid_candidate) {
5179                                 Some(_) => continue,
5180                                 None => return scid_candidate
5181                         }
5182                 }
5183         }
5184
5185         /// Gets route hints for use in receiving [phantom node payments].
5186         ///
5187         /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
5188         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
5189                 PhantomRouteHints {
5190                         channels: self.list_usable_channels(),
5191                         phantom_scid: self.get_phantom_scid(),
5192                         real_node_pubkey: self.get_our_node_id(),
5193                 }
5194         }
5195
5196         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
5197         /// used when constructing the route hints for HTLCs intended to be intercepted. See
5198         /// [`ChannelManager::forward_intercepted_htlc`].
5199         ///
5200         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
5201         /// times to get a unique scid.
5202         pub fn get_intercept_scid(&self) -> u64 {
5203                 let best_block_height = self.best_block.read().unwrap().height();
5204                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
5205                 loop {
5206                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.keys_manager);
5207                         // Ensure the generated scid doesn't conflict with a real channel.
5208                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
5209                         return scid_candidate
5210                 }
5211         }
5212
5213         /// Gets inflight HTLC information by processing pending outbound payments that are in
5214         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
5215         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
5216                 let mut inflight_htlcs = InFlightHtlcs::new();
5217
5218                 for chan in self.channel_state.lock().unwrap().by_id.values() {
5219                         for (htlc_source, _) in chan.inflight_htlc_sources() {
5220                                 if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
5221                                         inflight_htlcs.process_path(path, self.get_our_node_id());
5222                                 }
5223                         }
5224                 }
5225
5226                 inflight_htlcs
5227         }
5228
5229         #[cfg(any(test, fuzzing, feature = "_test_utils"))]
5230         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
5231                 let events = core::cell::RefCell::new(Vec::new());
5232                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
5233                 self.process_pending_events(&event_handler);
5234                 events.into_inner()
5235         }
5236
5237         #[cfg(test)]
5238         pub fn pop_pending_event(&self) -> Option<events::Event> {
5239                 let mut events = self.pending_events.lock().unwrap();
5240                 if events.is_empty() { None } else { Some(events.remove(0)) }
5241         }
5242
5243         #[cfg(test)]
5244         pub fn has_pending_payments(&self) -> bool {
5245                 self.pending_outbound_payments.has_pending_payments()
5246         }
5247
5248         #[cfg(test)]
5249         pub fn clear_pending_payments(&self) {
5250                 self.pending_outbound_payments.clear_pending_payments()
5251         }
5252
5253         /// Processes any events asynchronously in the order they were generated since the last call
5254         /// using the given event handler.
5255         ///
5256         /// See the trait-level documentation of [`EventsProvider`] for requirements.
5257         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
5258                 &self, handler: H
5259         ) {
5260                 // We'll acquire our total consistency lock until the returned future completes so that
5261                 // we can be sure no other persists happen while processing events.
5262                 let _read_guard = self.total_consistency_lock.read().unwrap();
5263
5264                 let mut result = NotifyOption::SkipPersist;
5265
5266                 // TODO: This behavior should be documented. It's unintuitive that we query
5267                 // ChannelMonitors when clearing other events.
5268                 if self.process_pending_monitor_events() {
5269                         result = NotifyOption::DoPersist;
5270                 }
5271
5272                 let pending_events = mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]);
5273                 if !pending_events.is_empty() {
5274                         result = NotifyOption::DoPersist;
5275                 }
5276
5277                 for event in pending_events {
5278                         handler(event).await;
5279                 }
5280
5281                 if result == NotifyOption::DoPersist {
5282                         self.persistence_notifier.notify();
5283                 }
5284         }
5285 }
5286
5287 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<M, T, K, F, R, L>
5288 where
5289         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
5290         T::Target: BroadcasterInterface,
5291         K::Target: KeysInterface,
5292         F::Target: FeeEstimator,
5293         R::Target: Router,
5294         L::Target: Logger,
5295 {
5296         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
5297                 let events = RefCell::new(Vec::new());
5298                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5299                         let mut result = NotifyOption::SkipPersist;
5300
5301                         // TODO: This behavior should be documented. It's unintuitive that we query
5302                         // ChannelMonitors when clearing other events.
5303                         if self.process_pending_monitor_events() {
5304                                 result = NotifyOption::DoPersist;
5305                         }
5306
5307                         if self.check_free_holding_cells() {
5308                                 result = NotifyOption::DoPersist;
5309                         }
5310                         if self.maybe_generate_initial_closing_signed() {
5311                                 result = NotifyOption::DoPersist;
5312                         }
5313
5314                         let mut pending_events = Vec::new();
5315                         let mut channel_state = self.channel_state.lock().unwrap();
5316                         mem::swap(&mut pending_events, &mut channel_state.pending_msg_events);
5317
5318                         if !pending_events.is_empty() {
5319                                 events.replace(pending_events);
5320                         }
5321
5322                         result
5323                 });
5324                 events.into_inner()
5325         }
5326 }
5327
5328 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref> EventsProvider for ChannelManager<M, T, K, F, R, L>
5329 where
5330         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
5331         T::Target: BroadcasterInterface,
5332         K::Target: KeysInterface,
5333         F::Target: FeeEstimator,
5334         R::Target: Router,
5335         L::Target: Logger,
5336 {
5337         /// Processes events that must be periodically handled.
5338         ///
5339         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
5340         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
5341         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
5342                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5343                         let mut result = NotifyOption::SkipPersist;
5344
5345                         // TODO: This behavior should be documented. It's unintuitive that we query
5346                         // ChannelMonitors when clearing other events.
5347                         if self.process_pending_monitor_events() {
5348                                 result = NotifyOption::DoPersist;
5349                         }
5350
5351                         let pending_events = mem::replace(&mut *self.pending_events.lock().unwrap(), vec![]);
5352                         if !pending_events.is_empty() {
5353                                 result = NotifyOption::DoPersist;
5354                         }
5355
5356                         for event in pending_events {
5357                                 handler.handle_event(event);
5358                         }
5359
5360                         result
5361                 });
5362         }
5363 }
5364
5365 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref> chain::Listen for ChannelManager<M, T, K, F, R, L>
5366 where
5367         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
5368         T::Target: BroadcasterInterface,
5369         K::Target: KeysInterface,
5370         F::Target: FeeEstimator,
5371         R::Target: Router,
5372         L::Target: Logger,
5373 {
5374         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
5375                 {
5376                         let best_block = self.best_block.read().unwrap();
5377                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
5378                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
5379                         assert_eq!(best_block.height(), height - 1,
5380                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
5381                 }
5382
5383                 self.transactions_confirmed(header, txdata, height);
5384                 self.best_block_updated(header, height);
5385         }
5386
5387         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
5388                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5389                 let new_height = height - 1;
5390                 {
5391                         let mut best_block = self.best_block.write().unwrap();
5392                         assert_eq!(best_block.block_hash(), header.block_hash(),
5393                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
5394                         assert_eq!(best_block.height(), height,
5395                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
5396                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
5397                 }
5398
5399                 self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.genesis_hash.clone(), self.get_our_node_id(), &self.logger));
5400         }
5401 }
5402
5403 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref> chain::Confirm for ChannelManager<M, T, K, F, R, L>
5404 where
5405         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
5406         T::Target: BroadcasterInterface,
5407         K::Target: KeysInterface,
5408         F::Target: FeeEstimator,
5409         R::Target: Router,
5410         L::Target: Logger,
5411 {
5412         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
5413                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5414                 // during initialization prior to the chain_monitor being fully configured in some cases.
5415                 // See the docs for `ChannelManagerReadArgs` for more.
5416
5417                 let block_hash = header.block_hash();
5418                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
5419
5420                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5421                 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.genesis_hash.clone(), self.get_our_node_id(), &self.logger)
5422                         .map(|(a, b)| (a, Vec::new(), b)));
5423
5424                 let last_best_block_height = self.best_block.read().unwrap().height();
5425                 if height < last_best_block_height {
5426                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
5427                         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.get_our_node_id(), &self.logger));
5428                 }
5429         }
5430
5431         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
5432                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5433                 // during initialization prior to the chain_monitor being fully configured in some cases.
5434                 // See the docs for `ChannelManagerReadArgs` for more.
5435
5436                 let block_hash = header.block_hash();
5437                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
5438
5439                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5440
5441                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
5442
5443                 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.genesis_hash.clone(), self.get_our_node_id(), &self.logger));
5444
5445                 macro_rules! max_time {
5446                         ($timestamp: expr) => {
5447                                 loop {
5448                                         // Update $timestamp to be the max of its current value and the block
5449                                         // timestamp. This should keep us close to the current time without relying on
5450                                         // having an explicit local time source.
5451                                         // Just in case we end up in a race, we loop until we either successfully
5452                                         // update $timestamp or decide we don't need to.
5453                                         let old_serial = $timestamp.load(Ordering::Acquire);
5454                                         if old_serial >= header.time as usize { break; }
5455                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
5456                                                 break;
5457                                         }
5458                                 }
5459                         }
5460                 }
5461                 max_time!(self.highest_seen_timestamp);
5462                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
5463                 payment_secrets.retain(|_, inbound_payment| {
5464                         inbound_payment.expiry_time > header.time as u64
5465                 });
5466         }
5467
5468         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
5469                 let channel_state = self.channel_state.lock().unwrap();
5470                 let mut res = Vec::with_capacity(channel_state.by_id.len());
5471                 for chan in channel_state.by_id.values() {
5472                         if let (Some(funding_txo), block_hash) = (chan.get_funding_txo(), chan.get_funding_tx_confirmed_in()) {
5473                                 res.push((funding_txo.txid, block_hash));
5474                         }
5475                 }
5476                 res
5477         }
5478
5479         fn transaction_unconfirmed(&self, txid: &Txid) {
5480                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5481                 self.do_chain_event(None, |channel| {
5482                         if let Some(funding_txo) = channel.get_funding_txo() {
5483                                 if funding_txo.txid == *txid {
5484                                         channel.funding_transaction_unconfirmed(&self.logger).map(|()| (None, Vec::new(), None))
5485                                 } else { Ok((None, Vec::new(), None)) }
5486                         } else { Ok((None, Vec::new(), None)) }
5487                 });
5488         }
5489 }
5490
5491 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref> ChannelManager<M, T, K, F, R, L>
5492 where
5493         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
5494         T::Target: BroadcasterInterface,
5495         K::Target: KeysInterface,
5496         F::Target: FeeEstimator,
5497         R::Target: Router,
5498         L::Target: Logger,
5499 {
5500         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
5501         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
5502         /// the function.
5503         fn do_chain_event<FN: Fn(&mut Channel<<K::Target as SignerProvider>::Signer>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
5504                         (&self, height_opt: Option<u32>, f: FN) {
5505                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5506                 // during initialization prior to the chain_monitor being fully configured in some cases.
5507                 // See the docs for `ChannelManagerReadArgs` for more.
5508
5509                 let mut failed_channels = Vec::new();
5510                 let mut timed_out_htlcs = Vec::new();
5511                 {
5512                         let mut channel_lock = self.channel_state.lock().unwrap();
5513                         let channel_state = &mut *channel_lock;
5514                         let pending_msg_events = &mut channel_state.pending_msg_events;
5515                         channel_state.by_id.retain(|_, channel| {
5516                                 let res = f(channel);
5517                                 if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
5518                                         for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
5519                                                 let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
5520                                                 timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
5521                                                         HTLCDestination::NextHopChannel { node_id: Some(channel.get_counterparty_node_id()), channel_id: channel.channel_id() }));
5522                                         }
5523                                         if let Some(channel_ready) = channel_ready_opt {
5524                                                 send_channel_ready!(self, pending_msg_events, channel, channel_ready);
5525                                                 if channel.is_usable() {
5526                                                         log_trace!(self.logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", log_bytes!(channel.channel_id()));
5527                                                         if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
5528                                                                 pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
5529                                                                         node_id: channel.get_counterparty_node_id(),
5530                                                                         msg,
5531                                                                 });
5532                                                         }
5533                                                 } else {
5534                                                         log_trace!(self.logger, "Sending channel_ready WITHOUT channel_update for {}", log_bytes!(channel.channel_id()));
5535                                                 }
5536                                         }
5537
5538                                         emit_channel_ready_event!(self, channel);
5539
5540                                         if let Some(announcement_sigs) = announcement_sigs {
5541                                                 log_trace!(self.logger, "Sending announcement_signatures for channel {}", log_bytes!(channel.channel_id()));
5542                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5543                                                         node_id: channel.get_counterparty_node_id(),
5544                                                         msg: announcement_sigs,
5545                                                 });
5546                                                 if let Some(height) = height_opt {
5547                                                         if let Some(announcement) = channel.get_signed_channel_announcement(self.get_our_node_id(), self.genesis_hash, height) {
5548                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
5549                                                                         msg: announcement,
5550                                                                         // Note that announcement_signatures fails if the channel cannot be announced,
5551                                                                         // so get_channel_update_for_broadcast will never fail by the time we get here.
5552                                                                         update_msg: self.get_channel_update_for_broadcast(channel).unwrap(),
5553                                                                 });
5554                                                         }
5555                                                 }
5556                                         }
5557                                         if channel.is_our_channel_ready() {
5558                                                 if let Some(real_scid) = channel.get_short_channel_id() {
5559                                                         // If we sent a 0conf channel_ready, and now have an SCID, we add it
5560                                                         // to the short_to_chan_info map here. Note that we check whether we
5561                                                         // can relay using the real SCID at relay-time (i.e.
5562                                                         // enforce option_scid_alias then), and if the funding tx is ever
5563                                                         // un-confirmed we force-close the channel, ensuring short_to_chan_info
5564                                                         // is always consistent.
5565                                                         let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
5566                                                         let scid_insert = short_to_chan_info.insert(real_scid, (channel.get_counterparty_node_id(), channel.channel_id()));
5567                                                         assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.get_counterparty_node_id(), channel.channel_id()),
5568                                                                 "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
5569                                                                 fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
5570                                                 }
5571                                         }
5572                                 } else if let Err(reason) = res {
5573                                         update_maps_on_chan_removal!(self, channel);
5574                                         // It looks like our counterparty went on-chain or funding transaction was
5575                                         // reorged out of the main chain. Close the channel.
5576                                         failed_channels.push(channel.force_shutdown(true));
5577                                         if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
5578                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5579                                                         msg: update
5580                                                 });
5581                                         }
5582                                         let reason_message = format!("{}", reason);
5583                                         self.issue_channel_close_events(channel, reason);
5584                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
5585                                                 node_id: channel.get_counterparty_node_id(),
5586                                                 action: msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage {
5587                                                         channel_id: channel.channel_id(),
5588                                                         data: reason_message,
5589                                                 } },
5590                                         });
5591                                         return false;
5592                                 }
5593                                 true
5594                         });
5595                 }
5596
5597                 if let Some(height) = height_opt {
5598                         self.claimable_payments.lock().unwrap().claimable_htlcs.retain(|payment_hash, (_, htlcs)| {
5599                                 htlcs.retain(|htlc| {
5600                                         // If height is approaching the number of blocks we think it takes us to get
5601                                         // our commitment transaction confirmed before the HTLC expires, plus the
5602                                         // number of blocks we generally consider it to take to do a commitment update,
5603                                         // just give up on it and fail the HTLC.
5604                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
5605                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5606                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
5607
5608                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
5609                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
5610                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
5611                                                 false
5612                                         } else { true }
5613                                 });
5614                                 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
5615                         });
5616
5617                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
5618                         intercepted_htlcs.retain(|_, htlc| {
5619                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
5620                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
5621                                                 short_channel_id: htlc.prev_short_channel_id,
5622                                                 htlc_id: htlc.prev_htlc_id,
5623                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
5624                                                 phantom_shared_secret: None,
5625                                                 outpoint: htlc.prev_funding_outpoint,
5626                                         });
5627
5628                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
5629                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
5630                                                 _ => unreachable!(),
5631                                         };
5632                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
5633                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
5634                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
5635                                         log_trace!(self.logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
5636                                         false
5637                                 } else { true }
5638                         });
5639                 }
5640
5641                 self.handle_init_event_channel_failures(failed_channels);
5642
5643                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
5644                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
5645                 }
5646         }
5647
5648         /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
5649         /// indicating whether persistence is necessary. Only one listener on
5650         /// [`await_persistable_update`], [`await_persistable_update_timeout`], or a future returned by
5651         /// [`get_persistable_update_future`] is guaranteed to be woken up.
5652         ///
5653         /// Note that this method is not available with the `no-std` feature.
5654         ///
5655         /// [`await_persistable_update`]: Self::await_persistable_update
5656         /// [`await_persistable_update_timeout`]: Self::await_persistable_update_timeout
5657         /// [`get_persistable_update_future`]: Self::get_persistable_update_future
5658         #[cfg(any(test, feature = "std"))]
5659         pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
5660                 self.persistence_notifier.wait_timeout(max_wait)
5661         }
5662
5663         /// Blocks until ChannelManager needs to be persisted. Only one listener on
5664         /// [`await_persistable_update`], `await_persistable_update_timeout`, or a future returned by
5665         /// [`get_persistable_update_future`] is guaranteed to be woken up.
5666         ///
5667         /// [`await_persistable_update`]: Self::await_persistable_update
5668         /// [`get_persistable_update_future`]: Self::get_persistable_update_future
5669         pub fn await_persistable_update(&self) {
5670                 self.persistence_notifier.wait()
5671         }
5672
5673         /// Gets a [`Future`] that completes when a persistable update is available. Note that
5674         /// callbacks registered on the [`Future`] MUST NOT call back into this [`ChannelManager`] and
5675         /// should instead register actions to be taken later.
5676         pub fn get_persistable_update_future(&self) -> Future {
5677                 self.persistence_notifier.get_future()
5678         }
5679
5680         #[cfg(any(test, feature = "_test_utils"))]
5681         pub fn get_persistence_condvar_value(&self) -> bool {
5682                 self.persistence_notifier.notify_pending()
5683         }
5684
5685         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
5686         /// [`chain::Confirm`] interfaces.
5687         pub fn current_best_block(&self) -> BestBlock {
5688                 self.best_block.read().unwrap().clone()
5689         }
5690 }
5691
5692 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref>
5693         ChannelMessageHandler for ChannelManager<M, T, K, F, R, L>
5694 where
5695         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
5696         T::Target: BroadcasterInterface,
5697         K::Target: KeysInterface,
5698         F::Target: FeeEstimator,
5699         R::Target: Router,
5700         L::Target: Logger,
5701 {
5702         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
5703                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5704                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
5705         }
5706
5707         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
5708                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5709                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
5710         }
5711
5712         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
5713                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5714                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
5715         }
5716
5717         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
5718                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5719                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
5720         }
5721
5722         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
5723                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5724                 let _ = handle_error!(self, self.internal_channel_ready(counterparty_node_id, msg), *counterparty_node_id);
5725         }
5726
5727         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
5728                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5729                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
5730         }
5731
5732         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
5733                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5734                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
5735         }
5736
5737         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
5738                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5739                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
5740         }
5741
5742         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
5743                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5744                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
5745         }
5746
5747         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
5748                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5749                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
5750         }
5751
5752         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
5753                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5754                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
5755         }
5756
5757         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
5758                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5759                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
5760         }
5761
5762         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
5763                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5764                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
5765         }
5766
5767         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
5768                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5769                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
5770         }
5771
5772         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
5773                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5774                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
5775         }
5776
5777         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
5778                 PersistenceNotifierGuard::optionally_notify(&self.total_consistency_lock, &self.persistence_notifier, || {
5779                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
5780                                 persist
5781                         } else {
5782                                 NotifyOption::SkipPersist
5783                         }
5784                 });
5785         }
5786
5787         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
5788                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5789                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
5790         }
5791
5792         fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
5793                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5794                 let mut failed_channels = Vec::new();
5795                 let mut no_channels_remain = true;
5796                 {
5797                         let mut channel_state_lock = self.channel_state.lock().unwrap();
5798                         let channel_state = &mut *channel_state_lock;
5799                         let pending_msg_events = &mut channel_state.pending_msg_events;
5800                         log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates. We believe we {} make future connections to this peer.",
5801                                 log_pubkey!(counterparty_node_id), if no_connection_possible { "cannot" } else { "can" });
5802                         channel_state.by_id.retain(|_, chan| {
5803                                 if chan.get_counterparty_node_id() == *counterparty_node_id {
5804                                         chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
5805                                         if chan.is_shutdown() {
5806                                                 update_maps_on_chan_removal!(self, chan);
5807                                                 self.issue_channel_close_events(chan, ClosureReason::DisconnectedPeer);
5808                                                 return false;
5809                                         } else {
5810                                                 no_channels_remain = false;
5811                                         }
5812                                 }
5813                                 true
5814                         });
5815                         pending_msg_events.retain(|msg| {
5816                                 match msg {
5817                                         &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != counterparty_node_id,
5818                                         &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != counterparty_node_id,
5819                                         &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != counterparty_node_id,
5820                                         &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != counterparty_node_id,
5821                                         &events::MessageSendEvent::SendChannelReady { ref node_id, .. } => node_id != counterparty_node_id,
5822                                         &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != counterparty_node_id,
5823                                         &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != counterparty_node_id,
5824                                         &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != counterparty_node_id,
5825                                         &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != counterparty_node_id,
5826                                         &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != counterparty_node_id,
5827                                         &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
5828                                         &events::MessageSendEvent::SendChannelAnnouncement { ref node_id, .. } => node_id != counterparty_node_id,
5829                                         &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
5830                                         &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
5831                                         &events::MessageSendEvent::SendChannelUpdate { ref node_id, .. } => node_id != counterparty_node_id,
5832                                         &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
5833                                         &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
5834                                         &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
5835                                         &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
5836                                         &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
5837                                 }
5838                         });
5839                 }
5840                 if no_channels_remain {
5841                         self.per_peer_state.write().unwrap().remove(counterparty_node_id);
5842                 }
5843
5844                 for failure in failed_channels.drain(..) {
5845                         self.finish_force_close_channel(failure);
5846                 }
5847         }
5848
5849         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
5850                 if !init_msg.features.supports_static_remote_key() {
5851                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(counterparty_node_id));
5852                         return Err(());
5853                 }
5854
5855                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
5856
5857                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5858
5859                 {
5860                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
5861                         match peer_state_lock.entry(counterparty_node_id.clone()) {
5862                                 hash_map::Entry::Vacant(e) => {
5863                                         e.insert(Mutex::new(PeerState {
5864                                                 latest_features: init_msg.features.clone(),
5865                                         }));
5866                                 },
5867                                 hash_map::Entry::Occupied(e) => {
5868                                         e.get().lock().unwrap().latest_features = init_msg.features.clone();
5869                                 },
5870                         }
5871                 }
5872
5873                 let mut channel_state_lock = self.channel_state.lock().unwrap();
5874                 let channel_state = &mut *channel_state_lock;
5875                 let pending_msg_events = &mut channel_state.pending_msg_events;
5876                 channel_state.by_id.retain(|_, chan| {
5877                         let retain = if chan.get_counterparty_node_id() == *counterparty_node_id {
5878                                 if !chan.have_received_message() {
5879                                         // If we created this (outbound) channel while we were disconnected from the
5880                                         // peer we probably failed to send the open_channel message, which is now
5881                                         // lost. We can't have had anything pending related to this channel, so we just
5882                                         // drop it.
5883                                         false
5884                                 } else {
5885                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
5886                                                 node_id: chan.get_counterparty_node_id(),
5887                                                 msg: chan.get_channel_reestablish(&self.logger),
5888                                         });
5889                                         true
5890                                 }
5891                         } else { true };
5892                         if retain && chan.get_counterparty_node_id() != *counterparty_node_id {
5893                                 if let Some(msg) = chan.get_signed_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone(), self.best_block.read().unwrap().height()) {
5894                                         if let Ok(update_msg) = self.get_channel_update_for_broadcast(chan) {
5895                                                 pending_msg_events.push(events::MessageSendEvent::SendChannelAnnouncement {
5896                                                         node_id: *counterparty_node_id,
5897                                                         msg, update_msg,
5898                                                 });
5899                                         }
5900                                 }
5901                         }
5902                         retain
5903                 });
5904                 //TODO: Also re-broadcast announcement_signatures
5905                 Ok(())
5906         }
5907
5908         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
5909                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
5910
5911                 if msg.channel_id == [0; 32] {
5912                         for chan in self.list_channels() {
5913                                 if chan.counterparty.node_id == *counterparty_node_id {
5914                                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
5915                                         let _ = self.force_close_channel_with_peer(&chan.channel_id, counterparty_node_id, Some(&msg.data), true);
5916                                 }
5917                         }
5918                 } else {
5919                         {
5920                                 // First check if we can advance the channel type and try again.
5921                                 let mut channel_state = self.channel_state.lock().unwrap();
5922                                 if let Some(chan) = channel_state.by_id.get_mut(&msg.channel_id) {
5923                                         if chan.get_counterparty_node_id() != *counterparty_node_id {
5924                                                 return;
5925                                         }
5926                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.genesis_hash) {
5927                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
5928                                                         node_id: *counterparty_node_id,
5929                                                         msg,
5930                                                 });
5931                                                 return;
5932                                         }
5933                                 }
5934                         }
5935
5936                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
5937                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
5938                 }
5939         }
5940
5941         fn provided_node_features(&self) -> NodeFeatures {
5942                 provided_node_features()
5943         }
5944
5945         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
5946                 provided_init_features()
5947         }
5948 }
5949
5950 /// Fetches the set of [`NodeFeatures`] flags which are provided by or required by
5951 /// [`ChannelManager`].
5952 pub fn provided_node_features() -> NodeFeatures {
5953         provided_init_features().to_context()
5954 }
5955
5956 /// Fetches the set of [`InvoiceFeatures`] flags which are provided by or required by
5957 /// [`ChannelManager`].
5958 ///
5959 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
5960 /// or not. Thus, this method is not public.
5961 #[cfg(any(feature = "_test_utils", test))]
5962 pub fn provided_invoice_features() -> InvoiceFeatures {
5963         provided_init_features().to_context()
5964 }
5965
5966 /// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by
5967 /// [`ChannelManager`].
5968 pub fn provided_channel_features() -> ChannelFeatures {
5969         provided_init_features().to_context()
5970 }
5971
5972 /// Fetches the set of [`InitFeatures`] flags which are provided by or required by
5973 /// [`ChannelManager`].
5974 pub fn provided_init_features() -> InitFeatures {
5975         // Note that if new features are added here which other peers may (eventually) require, we
5976         // should also add the corresponding (optional) bit to the ChannelMessageHandler impl for
5977         // ErroringMessageHandler.
5978         let mut features = InitFeatures::empty();
5979         features.set_data_loss_protect_optional();
5980         features.set_upfront_shutdown_script_optional();
5981         features.set_variable_length_onion_required();
5982         features.set_static_remote_key_required();
5983         features.set_payment_secret_required();
5984         features.set_basic_mpp_optional();
5985         features.set_wumbo_optional();
5986         features.set_shutdown_any_segwit_optional();
5987         features.set_channel_type_optional();
5988         features.set_scid_privacy_optional();
5989         features.set_zero_conf_optional();
5990         features
5991 }
5992
5993 const SERIALIZATION_VERSION: u8 = 1;
5994 const MIN_SERIALIZATION_VERSION: u8 = 1;
5995
5996 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
5997         (2, fee_base_msat, required),
5998         (4, fee_proportional_millionths, required),
5999         (6, cltv_expiry_delta, required),
6000 });
6001
6002 impl_writeable_tlv_based!(ChannelCounterparty, {
6003         (2, node_id, required),
6004         (4, features, required),
6005         (6, unspendable_punishment_reserve, required),
6006         (8, forwarding_info, option),
6007         (9, outbound_htlc_minimum_msat, option),
6008         (11, outbound_htlc_maximum_msat, option),
6009 });
6010
6011 impl Writeable for ChannelDetails {
6012         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6013                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
6014                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
6015                 let user_channel_id_low = self.user_channel_id as u64;
6016                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
6017                 write_tlv_fields!(writer, {
6018                         (1, self.inbound_scid_alias, option),
6019                         (2, self.channel_id, required),
6020                         (3, self.channel_type, option),
6021                         (4, self.counterparty, required),
6022                         (5, self.outbound_scid_alias, option),
6023                         (6, self.funding_txo, option),
6024                         (7, self.config, option),
6025                         (8, self.short_channel_id, option),
6026                         (9, self.confirmations, option),
6027                         (10, self.channel_value_satoshis, required),
6028                         (12, self.unspendable_punishment_reserve, option),
6029                         (14, user_channel_id_low, required),
6030                         (16, self.balance_msat, required),
6031                         (18, self.outbound_capacity_msat, required),
6032                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
6033                         // filled in, so we can safely unwrap it here.
6034                         (19, self.next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
6035                         (20, self.inbound_capacity_msat, required),
6036                         (22, self.confirmations_required, option),
6037                         (24, self.force_close_spend_delay, option),
6038                         (26, self.is_outbound, required),
6039                         (28, self.is_channel_ready, required),
6040                         (30, self.is_usable, required),
6041                         (32, self.is_public, required),
6042                         (33, self.inbound_htlc_minimum_msat, option),
6043                         (35, self.inbound_htlc_maximum_msat, option),
6044                         (37, user_channel_id_high_opt, option),
6045                 });
6046                 Ok(())
6047         }
6048 }
6049
6050 impl Readable for ChannelDetails {
6051         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6052                 init_and_read_tlv_fields!(reader, {
6053                         (1, inbound_scid_alias, option),
6054                         (2, channel_id, required),
6055                         (3, channel_type, option),
6056                         (4, counterparty, required),
6057                         (5, outbound_scid_alias, option),
6058                         (6, funding_txo, option),
6059                         (7, config, option),
6060                         (8, short_channel_id, option),
6061                         (9, confirmations, option),
6062                         (10, channel_value_satoshis, required),
6063                         (12, unspendable_punishment_reserve, option),
6064                         (14, user_channel_id_low, required),
6065                         (16, balance_msat, required),
6066                         (18, outbound_capacity_msat, required),
6067                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
6068                         // filled in, so we can safely unwrap it here.
6069                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
6070                         (20, inbound_capacity_msat, required),
6071                         (22, confirmations_required, option),
6072                         (24, force_close_spend_delay, option),
6073                         (26, is_outbound, required),
6074                         (28, is_channel_ready, required),
6075                         (30, is_usable, required),
6076                         (32, is_public, required),
6077                         (33, inbound_htlc_minimum_msat, option),
6078                         (35, inbound_htlc_maximum_msat, option),
6079                         (37, user_channel_id_high_opt, option),
6080                 });
6081
6082                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
6083                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
6084                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
6085                 let user_channel_id = user_channel_id_low as u128 +
6086                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
6087
6088                 Ok(Self {
6089                         inbound_scid_alias,
6090                         channel_id: channel_id.0.unwrap(),
6091                         channel_type,
6092                         counterparty: counterparty.0.unwrap(),
6093                         outbound_scid_alias,
6094                         funding_txo,
6095                         config,
6096                         short_channel_id,
6097                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
6098                         unspendable_punishment_reserve,
6099                         user_channel_id,
6100                         balance_msat: balance_msat.0.unwrap(),
6101                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
6102                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
6103                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
6104                         confirmations_required,
6105                         confirmations,
6106                         force_close_spend_delay,
6107                         is_outbound: is_outbound.0.unwrap(),
6108                         is_channel_ready: is_channel_ready.0.unwrap(),
6109                         is_usable: is_usable.0.unwrap(),
6110                         is_public: is_public.0.unwrap(),
6111                         inbound_htlc_minimum_msat,
6112                         inbound_htlc_maximum_msat,
6113                 })
6114         }
6115 }
6116
6117 impl_writeable_tlv_based!(PhantomRouteHints, {
6118         (2, channels, vec_type),
6119         (4, phantom_scid, required),
6120         (6, real_node_pubkey, required),
6121 });
6122
6123 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
6124         (0, Forward) => {
6125                 (0, onion_packet, required),
6126                 (2, short_channel_id, required),
6127         },
6128         (1, Receive) => {
6129                 (0, payment_data, required),
6130                 (1, phantom_shared_secret, option),
6131                 (2, incoming_cltv_expiry, required),
6132         },
6133         (2, ReceiveKeysend) => {
6134                 (0, payment_preimage, required),
6135                 (2, incoming_cltv_expiry, required),
6136         },
6137 ;);
6138
6139 impl_writeable_tlv_based!(PendingHTLCInfo, {
6140         (0, routing, required),
6141         (2, incoming_shared_secret, required),
6142         (4, payment_hash, required),
6143         (6, outgoing_amt_msat, required),
6144         (8, outgoing_cltv_value, required),
6145         (9, incoming_amt_msat, option),
6146 });
6147
6148
6149 impl Writeable for HTLCFailureMsg {
6150         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6151                 match self {
6152                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
6153                                 0u8.write(writer)?;
6154                                 channel_id.write(writer)?;
6155                                 htlc_id.write(writer)?;
6156                                 reason.write(writer)?;
6157                         },
6158                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
6159                                 channel_id, htlc_id, sha256_of_onion, failure_code
6160                         }) => {
6161                                 1u8.write(writer)?;
6162                                 channel_id.write(writer)?;
6163                                 htlc_id.write(writer)?;
6164                                 sha256_of_onion.write(writer)?;
6165                                 failure_code.write(writer)?;
6166                         },
6167                 }
6168                 Ok(())
6169         }
6170 }
6171
6172 impl Readable for HTLCFailureMsg {
6173         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6174                 let id: u8 = Readable::read(reader)?;
6175                 match id {
6176                         0 => {
6177                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
6178                                         channel_id: Readable::read(reader)?,
6179                                         htlc_id: Readable::read(reader)?,
6180                                         reason: Readable::read(reader)?,
6181                                 }))
6182                         },
6183                         1 => {
6184                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
6185                                         channel_id: Readable::read(reader)?,
6186                                         htlc_id: Readable::read(reader)?,
6187                                         sha256_of_onion: Readable::read(reader)?,
6188                                         failure_code: Readable::read(reader)?,
6189                                 }))
6190                         },
6191                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
6192                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
6193                         // messages contained in the variants.
6194                         // In version 0.0.101, support for reading the variants with these types was added, and
6195                         // we should migrate to writing these variants when UpdateFailHTLC or
6196                         // UpdateFailMalformedHTLC get TLV fields.
6197                         2 => {
6198                                 let length: BigSize = Readable::read(reader)?;
6199                                 let mut s = FixedLengthReader::new(reader, length.0);
6200                                 let res = Readable::read(&mut s)?;
6201                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
6202                                 Ok(HTLCFailureMsg::Relay(res))
6203                         },
6204                         3 => {
6205                                 let length: BigSize = Readable::read(reader)?;
6206                                 let mut s = FixedLengthReader::new(reader, length.0);
6207                                 let res = Readable::read(&mut s)?;
6208                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
6209                                 Ok(HTLCFailureMsg::Malformed(res))
6210                         },
6211                         _ => Err(DecodeError::UnknownRequiredFeature),
6212                 }
6213         }
6214 }
6215
6216 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
6217         (0, Forward),
6218         (1, Fail),
6219 );
6220
6221 impl_writeable_tlv_based!(HTLCPreviousHopData, {
6222         (0, short_channel_id, required),
6223         (1, phantom_shared_secret, option),
6224         (2, outpoint, required),
6225         (4, htlc_id, required),
6226         (6, incoming_packet_shared_secret, required)
6227 });
6228
6229 impl Writeable for ClaimableHTLC {
6230         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6231                 let (payment_data, keysend_preimage) = match &self.onion_payload {
6232                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
6233                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
6234                 };
6235                 write_tlv_fields!(writer, {
6236                         (0, self.prev_hop, required),
6237                         (1, self.total_msat, required),
6238                         (2, self.value, required),
6239                         (4, payment_data, option),
6240                         (6, self.cltv_expiry, required),
6241                         (8, keysend_preimage, option),
6242                 });
6243                 Ok(())
6244         }
6245 }
6246
6247 impl Readable for ClaimableHTLC {
6248         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6249                 let mut prev_hop = crate::util::ser::OptionDeserWrapper(None);
6250                 let mut value = 0;
6251                 let mut payment_data: Option<msgs::FinalOnionHopData> = None;
6252                 let mut cltv_expiry = 0;
6253                 let mut total_msat = None;
6254                 let mut keysend_preimage: Option<PaymentPreimage> = None;
6255                 read_tlv_fields!(reader, {
6256                         (0, prev_hop, required),
6257                         (1, total_msat, option),
6258                         (2, value, required),
6259                         (4, payment_data, option),
6260                         (6, cltv_expiry, required),
6261                         (8, keysend_preimage, option)
6262                 });
6263                 let onion_payload = match keysend_preimage {
6264                         Some(p) => {
6265                                 if payment_data.is_some() {
6266                                         return Err(DecodeError::InvalidValue)
6267                                 }
6268                                 if total_msat.is_none() {
6269                                         total_msat = Some(value);
6270                                 }
6271                                 OnionPayload::Spontaneous(p)
6272                         },
6273                         None => {
6274                                 if total_msat.is_none() {
6275                                         if payment_data.is_none() {
6276                                                 return Err(DecodeError::InvalidValue)
6277                                         }
6278                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
6279                                 }
6280                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
6281                         },
6282                 };
6283                 Ok(Self {
6284                         prev_hop: prev_hop.0.unwrap(),
6285                         timer_ticks: 0,
6286                         value,
6287                         total_msat: total_msat.unwrap(),
6288                         onion_payload,
6289                         cltv_expiry,
6290                 })
6291         }
6292 }
6293
6294 impl Readable for HTLCSource {
6295         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
6296                 let id: u8 = Readable::read(reader)?;
6297                 match id {
6298                         0 => {
6299                                 let mut session_priv: crate::util::ser::OptionDeserWrapper<SecretKey> = crate::util::ser::OptionDeserWrapper(None);
6300                                 let mut first_hop_htlc_msat: u64 = 0;
6301                                 let mut path = Some(Vec::new());
6302                                 let mut payment_id = None;
6303                                 let mut payment_secret = None;
6304                                 let mut payment_params = None;
6305                                 read_tlv_fields!(reader, {
6306                                         (0, session_priv, required),
6307                                         (1, payment_id, option),
6308                                         (2, first_hop_htlc_msat, required),
6309                                         (3, payment_secret, option),
6310                                         (4, path, vec_type),
6311                                         (5, payment_params, option),
6312                                 });
6313                                 if payment_id.is_none() {
6314                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
6315                                         // instead.
6316                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
6317                                 }
6318                                 Ok(HTLCSource::OutboundRoute {
6319                                         session_priv: session_priv.0.unwrap(),
6320                                         first_hop_htlc_msat,
6321                                         path: path.unwrap(),
6322                                         payment_id: payment_id.unwrap(),
6323                                         payment_secret,
6324                                         payment_params,
6325                                 })
6326                         }
6327                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
6328                         _ => Err(DecodeError::UnknownRequiredFeature),
6329                 }
6330         }
6331 }
6332
6333 impl Writeable for HTLCSource {
6334         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
6335                 match self {
6336                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id, payment_secret, payment_params } => {
6337                                 0u8.write(writer)?;
6338                                 let payment_id_opt = Some(payment_id);
6339                                 write_tlv_fields!(writer, {
6340                                         (0, session_priv, required),
6341                                         (1, payment_id_opt, option),
6342                                         (2, first_hop_htlc_msat, required),
6343                                         (3, payment_secret, option),
6344                                         (4, *path, vec_type),
6345                                         (5, payment_params, option),
6346                                  });
6347                         }
6348                         HTLCSource::PreviousHopData(ref field) => {
6349                                 1u8.write(writer)?;
6350                                 field.write(writer)?;
6351                         }
6352                 }
6353                 Ok(())
6354         }
6355 }
6356
6357 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
6358         (0, forward_info, required),
6359         (1, prev_user_channel_id, (default_value, 0)),
6360         (2, prev_short_channel_id, required),
6361         (4, prev_htlc_id, required),
6362         (6, prev_funding_outpoint, required),
6363 });
6364
6365 impl_writeable_tlv_based_enum!(HTLCForwardInfo,
6366         (1, FailHTLC) => {
6367                 (0, htlc_id, required),
6368                 (2, err_packet, required),
6369         };
6370         (0, AddHTLC)
6371 );
6372
6373 impl_writeable_tlv_based!(PendingInboundPayment, {
6374         (0, payment_secret, required),
6375         (2, expiry_time, required),
6376         (4, user_payment_id, required),
6377         (6, payment_preimage, required),
6378         (8, min_value_msat, required),
6379 });
6380
6381 impl<M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref> Writeable for ChannelManager<M, T, K, F, R, L>
6382 where
6383         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
6384         T::Target: BroadcasterInterface,
6385         K::Target: KeysInterface,
6386         F::Target: FeeEstimator,
6387         R::Target: Router,
6388         L::Target: Logger,
6389 {
6390         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6391                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
6392
6393                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
6394
6395                 self.genesis_hash.write(writer)?;
6396                 {
6397                         let best_block = self.best_block.read().unwrap();
6398                         best_block.height().write(writer)?;
6399                         best_block.block_hash().write(writer)?;
6400                 }
6401
6402                 {
6403                         // Take `channel_state` lock temporarily to avoid creating a lock order that requires
6404                         // that the `forward_htlcs` lock is taken after `channel_state`
6405                         let channel_state = self.channel_state.lock().unwrap();
6406                         let mut unfunded_channels = 0;
6407                         for (_, channel) in channel_state.by_id.iter() {
6408                                 if !channel.is_funding_initiated() {
6409                                         unfunded_channels += 1;
6410                                 }
6411                         }
6412                         ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
6413                         for (_, channel) in channel_state.by_id.iter() {
6414                                 if channel.is_funding_initiated() {
6415                                         channel.write(writer)?;
6416                                 }
6417                         }
6418                 }
6419
6420                 {
6421                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
6422                         (forward_htlcs.len() as u64).write(writer)?;
6423                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
6424                                 short_channel_id.write(writer)?;
6425                                 (pending_forwards.len() as u64).write(writer)?;
6426                                 for forward in pending_forwards {
6427                                         forward.write(writer)?;
6428                                 }
6429                         }
6430                 }
6431
6432                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
6433                 let claimable_payments = self.claimable_payments.lock().unwrap();
6434                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
6435
6436                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
6437                 (claimable_payments.claimable_htlcs.len() as u64).write(writer)?;
6438                 for (payment_hash, (purpose, previous_hops)) in claimable_payments.claimable_htlcs.iter() {
6439                         payment_hash.write(writer)?;
6440                         (previous_hops.len() as u64).write(writer)?;
6441                         for htlc in previous_hops.iter() {
6442                                 htlc.write(writer)?;
6443                         }
6444                         htlc_purposes.push(purpose);
6445                 }
6446
6447                 let per_peer_state = self.per_peer_state.write().unwrap();
6448                 (per_peer_state.len() as u64).write(writer)?;
6449                 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
6450                         peer_pubkey.write(writer)?;
6451                         let peer_state = peer_state_mutex.lock().unwrap();
6452                         peer_state.latest_features.write(writer)?;
6453                 }
6454
6455                 let events = self.pending_events.lock().unwrap();
6456                 (events.len() as u64).write(writer)?;
6457                 for event in events.iter() {
6458                         event.write(writer)?;
6459                 }
6460
6461                 let background_events = self.pending_background_events.lock().unwrap();
6462                 (background_events.len() as u64).write(writer)?;
6463                 for event in background_events.iter() {
6464                         match event {
6465                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
6466                                         0u8.write(writer)?;
6467                                         funding_txo.write(writer)?;
6468                                         monitor_update.write(writer)?;
6469                                 },
6470                         }
6471                 }
6472
6473                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
6474                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
6475                 // likely to be identical.
6476                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
6477                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
6478
6479                 (pending_inbound_payments.len() as u64).write(writer)?;
6480                 for (hash, pending_payment) in pending_inbound_payments.iter() {
6481                         hash.write(writer)?;
6482                         pending_payment.write(writer)?;
6483                 }
6484
6485                 // For backwards compat, write the session privs and their total length.
6486                 let mut num_pending_outbounds_compat: u64 = 0;
6487                 for (_, outbound) in pending_outbound_payments.iter() {
6488                         if !outbound.is_fulfilled() && !outbound.abandoned() {
6489                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
6490                         }
6491                 }
6492                 num_pending_outbounds_compat.write(writer)?;
6493                 for (_, outbound) in pending_outbound_payments.iter() {
6494                         match outbound {
6495                                 PendingOutboundPayment::Legacy { session_privs } |
6496                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
6497                                         for session_priv in session_privs.iter() {
6498                                                 session_priv.write(writer)?;
6499                                         }
6500                                 }
6501                                 PendingOutboundPayment::Fulfilled { .. } => {},
6502                                 PendingOutboundPayment::Abandoned { .. } => {},
6503                         }
6504                 }
6505
6506                 // Encode without retry info for 0.0.101 compatibility.
6507                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
6508                 for (id, outbound) in pending_outbound_payments.iter() {
6509                         match outbound {
6510                                 PendingOutboundPayment::Legacy { session_privs } |
6511                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
6512                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
6513                                 },
6514                                 _ => {},
6515                         }
6516                 }
6517
6518                 let mut pending_intercepted_htlcs = None;
6519                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6520                 if our_pending_intercepts.len() != 0 {
6521                         pending_intercepted_htlcs = Some(our_pending_intercepts);
6522                 }
6523
6524                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
6525                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
6526                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
6527                         // map. Thus, if there are no entries we skip writing a TLV for it.
6528                         pending_claiming_payments = None;
6529                 } else {
6530                         debug_assert!(false, "While we have code to serialize pending_claiming_payments, the map should always be empty until a later PR");
6531                 }
6532
6533                 write_tlv_fields!(writer, {
6534                         (1, pending_outbound_payments_no_retry, required),
6535                         (2, pending_intercepted_htlcs, option),
6536                         (3, pending_outbound_payments, required),
6537                         (4, pending_claiming_payments, option),
6538                         (5, self.our_network_pubkey, required),
6539                         (7, self.fake_scid_rand_bytes, required),
6540                         (9, htlc_purposes, vec_type),
6541                         (11, self.probing_cookie_secret, required),
6542                 });
6543
6544                 Ok(())
6545         }
6546 }
6547
6548 /// Arguments for the creation of a ChannelManager that are not deserialized.
6549 ///
6550 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
6551 /// is:
6552 /// 1) Deserialize all stored [`ChannelMonitor`]s.
6553 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
6554 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
6555 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
6556 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
6557 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
6558 ///    same way you would handle a [`chain::Filter`] call using
6559 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
6560 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
6561 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
6562 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
6563 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
6564 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
6565 ///    the next step.
6566 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
6567 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
6568 ///
6569 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
6570 /// call any other methods on the newly-deserialized [`ChannelManager`].
6571 ///
6572 /// Note that because some channels may be closed during deserialization, it is critical that you
6573 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
6574 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
6575 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
6576 /// not force-close the same channels but consider them live), you may end up revoking a state for
6577 /// which you've already broadcasted the transaction.
6578 ///
6579 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
6580 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref>
6581 where
6582         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
6583         T::Target: BroadcasterInterface,
6584         K::Target: KeysInterface,
6585         F::Target: FeeEstimator,
6586         R::Target: Router,
6587         L::Target: Logger,
6588 {
6589         /// The keys provider which will give us relevant keys. Some keys will be loaded during
6590         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
6591         /// signing data.
6592         pub keys_manager: K,
6593
6594         /// The fee_estimator for use in the ChannelManager in the future.
6595         ///
6596         /// No calls to the FeeEstimator will be made during deserialization.
6597         pub fee_estimator: F,
6598         /// The chain::Watch for use in the ChannelManager in the future.
6599         ///
6600         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
6601         /// you have deserialized ChannelMonitors separately and will add them to your
6602         /// chain::Watch after deserializing this ChannelManager.
6603         pub chain_monitor: M,
6604
6605         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
6606         /// used to broadcast the latest local commitment transactions of channels which must be
6607         /// force-closed during deserialization.
6608         pub tx_broadcaster: T,
6609         /// The router which will be used in the ChannelManager in the future for finding routes
6610         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
6611         ///
6612         /// No calls to the router will be made during deserialization.
6613         pub router: R,
6614         /// The Logger for use in the ChannelManager and which may be used to log information during
6615         /// deserialization.
6616         pub logger: L,
6617         /// Default settings used for new channels. Any existing channels will continue to use the
6618         /// runtime settings which were stored when the ChannelManager was serialized.
6619         pub default_config: UserConfig,
6620
6621         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
6622         /// value.get_funding_txo() should be the key).
6623         ///
6624         /// If a monitor is inconsistent with the channel state during deserialization the channel will
6625         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
6626         /// is true for missing channels as well. If there is a monitor missing for which we find
6627         /// channel data Err(DecodeError::InvalidValue) will be returned.
6628         ///
6629         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
6630         /// this struct.
6631         ///
6632         /// (C-not exported) because we have no HashMap bindings
6633         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<K::Target as SignerProvider>::Signer>>,
6634 }
6635
6636 impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref>
6637                 ChannelManagerReadArgs<'a, M, T, K, F, R, L>
6638 where
6639         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
6640         T::Target: BroadcasterInterface,
6641         K::Target: KeysInterface,
6642         F::Target: FeeEstimator,
6643         R::Target: Router,
6644         L::Target: Logger,
6645 {
6646         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
6647         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
6648         /// populate a HashMap directly from C.
6649         pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, default_config: UserConfig,
6650                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<K::Target as SignerProvider>::Signer>>) -> Self {
6651                 Self {
6652                         keys_manager, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
6653                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
6654                 }
6655         }
6656 }
6657
6658 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
6659 // SipmleArcChannelManager type:
6660 impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref>
6661         ReadableArgs<ChannelManagerReadArgs<'a, M, T, K, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, K, F, R, L>>)
6662 where
6663         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
6664         T::Target: BroadcasterInterface,
6665         K::Target: KeysInterface,
6666         F::Target: FeeEstimator,
6667         R::Target: Router,
6668         L::Target: Logger,
6669 {
6670         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, K, F, R, L>) -> Result<Self, DecodeError> {
6671                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, K, F, R, L>)>::read(reader, args)?;
6672                 Ok((blockhash, Arc::new(chan_manager)))
6673         }
6674 }
6675
6676 impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref>
6677         ReadableArgs<ChannelManagerReadArgs<'a, M, T, K, F, R, L>> for (BlockHash, ChannelManager<M, T, K, F, R, L>)
6678 where
6679         M::Target: chain::Watch<<K::Target as SignerProvider>::Signer>,
6680         T::Target: BroadcasterInterface,
6681         K::Target: KeysInterface,
6682         F::Target: FeeEstimator,
6683         R::Target: Router,
6684         L::Target: Logger,
6685 {
6686         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, K, F, R, L>) -> Result<Self, DecodeError> {
6687                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
6688
6689                 let genesis_hash: BlockHash = Readable::read(reader)?;
6690                 let best_block_height: u32 = Readable::read(reader)?;
6691                 let best_block_hash: BlockHash = Readable::read(reader)?;
6692
6693                 let mut failed_htlcs = Vec::new();
6694
6695                 let channel_count: u64 = Readable::read(reader)?;
6696                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
6697                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
6698                 let mut id_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
6699                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
6700                 let mut channel_closures = Vec::new();
6701                 for _ in 0..channel_count {
6702                         let mut channel: Channel<<K::Target as SignerProvider>::Signer> = Channel::read(reader, (&args.keys_manager, best_block_height))?;
6703                         let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
6704                         funding_txo_set.insert(funding_txo.clone());
6705                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
6706                                 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
6707                                                 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
6708                                                 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
6709                                                 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
6710                                         // If the channel is ahead of the monitor, return InvalidValue:
6711                                         log_error!(args.logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
6712                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
6713                                                 log_bytes!(channel.channel_id()), monitor.get_latest_update_id(), channel.get_latest_monitor_update_id());
6714                                         log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
6715                                         log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
6716                                         log_error!(args.logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
6717                                         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");
6718                                         return Err(DecodeError::InvalidValue);
6719                                 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
6720                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
6721                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
6722                                                 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
6723                                         // But if the channel is behind of the monitor, close the channel:
6724                                         log_error!(args.logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
6725                                         log_error!(args.logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
6726                                         log_error!(args.logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
6727                                                 log_bytes!(channel.channel_id()), monitor.get_latest_update_id(), channel.get_latest_monitor_update_id());
6728                                         let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
6729                                         failed_htlcs.append(&mut new_failed_htlcs);
6730                                         monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
6731                                         channel_closures.push(events::Event::ChannelClosed {
6732                                                 channel_id: channel.channel_id(),
6733                                                 user_channel_id: channel.get_user_id(),
6734                                                 reason: ClosureReason::OutdatedChannelManager
6735                                         });
6736                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
6737                                                 let mut found_htlc = false;
6738                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
6739                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
6740                                                 }
6741                                                 if !found_htlc {
6742                                                         // If we have some HTLCs in the channel which are not present in the newer
6743                                                         // ChannelMonitor, they have been removed and should be failed back to
6744                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
6745                                                         // were actually claimed we'd have generated and ensured the previous-hop
6746                                                         // claim update ChannelMonitor updates were persisted prior to persising
6747                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
6748                                                         // backwards leg of the HTLC will simply be rejected.
6749                                                         log_info!(args.logger,
6750                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
6751                                                                 log_bytes!(channel.channel_id()), log_bytes!(payment_hash.0));
6752                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.get_counterparty_node_id(), channel.channel_id()));
6753                                                 }
6754                                         }
6755                                 } else {
6756                                         log_info!(args.logger, "Successfully loaded channel {}", log_bytes!(channel.channel_id()));
6757                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
6758                                                 short_to_chan_info.insert(short_channel_id, (channel.get_counterparty_node_id(), channel.channel_id()));
6759                                         }
6760                                         if channel.is_funding_initiated() {
6761                                                 id_to_peer.insert(channel.channel_id(), channel.get_counterparty_node_id());
6762                                         }
6763                                         by_id.insert(channel.channel_id(), channel);
6764                                 }
6765                         } else if channel.is_awaiting_initial_mon_persist() {
6766                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
6767                                 // was in-progress, we never broadcasted the funding transaction and can still
6768                                 // safely discard the channel.
6769                                 let _ = channel.force_shutdown(false);
6770                                 channel_closures.push(events::Event::ChannelClosed {
6771                                         channel_id: channel.channel_id(),
6772                                         user_channel_id: channel.get_user_id(),
6773                                         reason: ClosureReason::DisconnectedPeer,
6774                                 });
6775                         } else {
6776                                 log_error!(args.logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", log_bytes!(channel.channel_id()));
6777                                 log_error!(args.logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
6778                                 log_error!(args.logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
6779                                 log_error!(args.logger, " Without the ChannelMonitor we cannot continue without risking funds.");
6780                                 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");
6781                                 return Err(DecodeError::InvalidValue);
6782                         }
6783                 }
6784
6785                 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
6786                         if !funding_txo_set.contains(funding_txo) {
6787                                 log_info!(args.logger, "Broadcasting latest holder commitment transaction for closed channel {}", log_bytes!(funding_txo.to_channel_id()));
6788                                 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
6789                         }
6790                 }
6791
6792                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
6793                 let forward_htlcs_count: u64 = Readable::read(reader)?;
6794                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
6795                 for _ in 0..forward_htlcs_count {
6796                         let short_channel_id = Readable::read(reader)?;
6797                         let pending_forwards_count: u64 = Readable::read(reader)?;
6798                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
6799                         for _ in 0..pending_forwards_count {
6800                                 pending_forwards.push(Readable::read(reader)?);
6801                         }
6802                         forward_htlcs.insert(short_channel_id, pending_forwards);
6803                 }
6804
6805                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
6806                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
6807                 for _ in 0..claimable_htlcs_count {
6808                         let payment_hash = Readable::read(reader)?;
6809                         let previous_hops_len: u64 = Readable::read(reader)?;
6810                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
6811                         for _ in 0..previous_hops_len {
6812                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
6813                         }
6814                         claimable_htlcs_list.push((payment_hash, previous_hops));
6815                 }
6816
6817                 let peer_count: u64 = Readable::read(reader)?;
6818                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
6819                 for _ in 0..peer_count {
6820                         let peer_pubkey = Readable::read(reader)?;
6821                         let peer_state = PeerState {
6822                                 latest_features: Readable::read(reader)?,
6823                         };
6824                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
6825                 }
6826
6827                 let event_count: u64 = Readable::read(reader)?;
6828                 let mut pending_events_read: Vec<events::Event> = Vec::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<events::Event>()));
6829                 for _ in 0..event_count {
6830                         match MaybeReadable::read(reader)? {
6831                                 Some(event) => pending_events_read.push(event),
6832                                 None => continue,
6833                         }
6834                 }
6835
6836                 let background_event_count: u64 = Readable::read(reader)?;
6837                 let mut pending_background_events_read: Vec<BackgroundEvent> = Vec::with_capacity(cmp::min(background_event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<BackgroundEvent>()));
6838                 for _ in 0..background_event_count {
6839                         match <u8 as Readable>::read(reader)? {
6840                                 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
6841                                 _ => return Err(DecodeError::InvalidValue),
6842                         }
6843                 }
6844
6845                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
6846                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
6847
6848                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
6849                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
6850                 for _ in 0..pending_inbound_payment_count {
6851                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
6852                                 return Err(DecodeError::InvalidValue);
6853                         }
6854                 }
6855
6856                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
6857                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
6858                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
6859                 for _ in 0..pending_outbound_payments_count_compat {
6860                         let session_priv = Readable::read(reader)?;
6861                         let payment = PendingOutboundPayment::Legacy {
6862                                 session_privs: [session_priv].iter().cloned().collect()
6863                         };
6864                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
6865                                 return Err(DecodeError::InvalidValue)
6866                         };
6867                 }
6868
6869                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
6870                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
6871                 let mut pending_outbound_payments = None;
6872                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
6873                 let mut received_network_pubkey: Option<PublicKey> = None;
6874                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
6875                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
6876                 let mut claimable_htlc_purposes = None;
6877                 let mut pending_claiming_payments = Some(HashMap::new());
6878                 read_tlv_fields!(reader, {
6879                         (1, pending_outbound_payments_no_retry, option),
6880                         (2, pending_intercepted_htlcs, option),
6881                         (3, pending_outbound_payments, option),
6882                         (4, pending_claiming_payments, option),
6883                         (5, received_network_pubkey, option),
6884                         (7, fake_scid_rand_bytes, option),
6885                         (9, claimable_htlc_purposes, vec_type),
6886                         (11, probing_cookie_secret, option),
6887                 });
6888                 if fake_scid_rand_bytes.is_none() {
6889                         fake_scid_rand_bytes = Some(args.keys_manager.get_secure_random_bytes());
6890                 }
6891
6892                 if probing_cookie_secret.is_none() {
6893                         probing_cookie_secret = Some(args.keys_manager.get_secure_random_bytes());
6894                 }
6895
6896                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
6897                         pending_outbound_payments = Some(pending_outbound_payments_compat);
6898                 } else if pending_outbound_payments.is_none() {
6899                         let mut outbounds = HashMap::new();
6900                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
6901                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
6902                         }
6903                         pending_outbound_payments = Some(outbounds);
6904                 } else {
6905                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
6906                         // ChannelMonitor data for any channels for which we do not have authorative state
6907                         // (i.e. those for which we just force-closed above or we otherwise don't have a
6908                         // corresponding `Channel` at all).
6909                         // This avoids several edge-cases where we would otherwise "forget" about pending
6910                         // payments which are still in-flight via their on-chain state.
6911                         // We only rebuild the pending payments map if we were most recently serialized by
6912                         // 0.0.102+
6913                         for (_, monitor) in args.channel_monitors.iter() {
6914                                 if by_id.get(&monitor.get_funding_txo().0.to_channel_id()).is_none() {
6915                                         for (htlc_source, htlc) in monitor.get_pending_outbound_htlcs() {
6916                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, payment_secret, .. } = htlc_source {
6917                                                         if path.is_empty() {
6918                                                                 log_error!(args.logger, "Got an empty path for a pending payment");
6919                                                                 return Err(DecodeError::InvalidValue);
6920                                                         }
6921                                                         let path_amt = path.last().unwrap().fee_msat;
6922                                                         let mut session_priv_bytes = [0; 32];
6923                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
6924                                                         match pending_outbound_payments.as_mut().unwrap().entry(payment_id) {
6925                                                                 hash_map::Entry::Occupied(mut entry) => {
6926                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
6927                                                                         log_info!(args.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
6928                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), log_bytes!(htlc.payment_hash.0));
6929                                                                 },
6930                                                                 hash_map::Entry::Vacant(entry) => {
6931                                                                         let path_fee = path.get_path_fees();
6932                                                                         entry.insert(PendingOutboundPayment::Retryable {
6933                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
6934                                                                                 payment_hash: htlc.payment_hash,
6935                                                                                 payment_secret,
6936                                                                                 pending_amt_msat: path_amt,
6937                                                                                 pending_fee_msat: Some(path_fee),
6938                                                                                 total_msat: path_amt,
6939                                                                                 starting_block_height: best_block_height,
6940                                                                         });
6941                                                                         log_info!(args.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
6942                                                                                 path_amt, log_bytes!(htlc.payment_hash.0),  log_bytes!(session_priv_bytes));
6943                                                                 }
6944                                                         }
6945                                                 }
6946                                         }
6947                                         for (htlc_source, htlc) in monitor.get_all_current_outbound_htlcs() {
6948                                                 if let HTLCSource::PreviousHopData(prev_hop_data) = htlc_source {
6949                                                         let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
6950                                                                 info.prev_funding_outpoint == prev_hop_data.outpoint &&
6951                                                                         info.prev_htlc_id == prev_hop_data.htlc_id
6952                                                         };
6953                                                         // The ChannelMonitor is now responsible for this HTLC's
6954                                                         // failure/success and will let us know what its outcome is. If we
6955                                                         // still have an entry for this HTLC in `forward_htlcs` or
6956                                                         // `pending_intercepted_htlcs`, we were apparently not persisted after
6957                                                         // the monitor was when forwarding the payment.
6958                                                         forward_htlcs.retain(|_, forwards| {
6959                                                                 forwards.retain(|forward| {
6960                                                                         if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
6961                                                                                 if pending_forward_matches_htlc(&htlc_info) {
6962                                                                                         log_info!(args.logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
6963                                                                                                 log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
6964                                                                                         false
6965                                                                                 } else { true }
6966                                                                         } else { true }
6967                                                                 });
6968                                                                 !forwards.is_empty()
6969                                                         });
6970                                                         pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
6971                                                                 if pending_forward_matches_htlc(&htlc_info) {
6972                                                                         log_info!(args.logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
6973                                                                                 log_bytes!(htlc.payment_hash.0), log_bytes!(monitor.get_funding_txo().0.to_channel_id()));
6974                                                                         pending_events_read.retain(|event| {
6975                                                                                 if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
6976                                                                                         intercepted_id != ev_id
6977                                                                                 } else { true }
6978                                                                         });
6979                                                                         false
6980                                                                 } else { true }
6981                                                         });
6982                                                 }
6983                                         }
6984                                 }
6985                         }
6986                 }
6987
6988                 if !forward_htlcs.is_empty() {
6989                         // If we have pending HTLCs to forward, assume we either dropped a
6990                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
6991                         // shut down before the timer hit. Either way, set the time_forwardable to a small
6992                         // constant as enough time has likely passed that we should simply handle the forwards
6993                         // now, or at least after the user gets a chance to reconnect to our peers.
6994                         pending_events_read.push(events::Event::PendingHTLCsForwardable {
6995                                 time_forwardable: Duration::from_secs(2),
6996                         });
6997                 }
6998
6999                 let inbound_pmt_key_material = args.keys_manager.get_inbound_payment_key_material();
7000                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
7001
7002                 let mut claimable_htlcs = HashMap::with_capacity(claimable_htlcs_list.len());
7003                 if let Some(mut purposes) = claimable_htlc_purposes {
7004                         if purposes.len() != claimable_htlcs_list.len() {
7005                                 return Err(DecodeError::InvalidValue);
7006                         }
7007                         for (purpose, (payment_hash, previous_hops)) in purposes.drain(..).zip(claimable_htlcs_list.drain(..)) {
7008                                 claimable_htlcs.insert(payment_hash, (purpose, previous_hops));
7009                         }
7010                 } else {
7011                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
7012                         // include a `_legacy_hop_data` in the `OnionPayload`.
7013                         for (payment_hash, previous_hops) in claimable_htlcs_list.drain(..) {
7014                                 if previous_hops.is_empty() {
7015                                         return Err(DecodeError::InvalidValue);
7016                                 }
7017                                 let purpose = match &previous_hops[0].onion_payload {
7018                                         OnionPayload::Invoice { _legacy_hop_data } => {
7019                                                 if let Some(hop_data) = _legacy_hop_data {
7020                                                         events::PaymentPurpose::InvoicePayment {
7021                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
7022                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
7023                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
7024                                                                                 Ok(payment_preimage) => payment_preimage,
7025                                                                                 Err(()) => {
7026                                                                                         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));
7027                                                                                         return Err(DecodeError::InvalidValue);
7028                                                                                 }
7029                                                                         }
7030                                                                 },
7031                                                                 payment_secret: hop_data.payment_secret,
7032                                                         }
7033                                                 } else { return Err(DecodeError::InvalidValue); }
7034                                         },
7035                                         OnionPayload::Spontaneous(payment_preimage) =>
7036                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
7037                                 };
7038                                 claimable_htlcs.insert(payment_hash, (purpose, previous_hops));
7039                         }
7040                 }
7041
7042                 let mut secp_ctx = Secp256k1::new();
7043                 secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
7044
7045                 if !channel_closures.is_empty() {
7046                         pending_events_read.append(&mut channel_closures);
7047                 }
7048
7049                 let our_network_key = match args.keys_manager.get_node_secret(Recipient::Node) {
7050                         Ok(key) => key,
7051                         Err(()) => return Err(DecodeError::InvalidValue)
7052                 };
7053                 let our_network_pubkey = PublicKey::from_secret_key(&secp_ctx, &our_network_key);
7054                 if let Some(network_pubkey) = received_network_pubkey {
7055                         if network_pubkey != our_network_pubkey {
7056                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
7057                                 return Err(DecodeError::InvalidValue);
7058                         }
7059                 }
7060
7061                 let mut outbound_scid_aliases = HashSet::new();
7062                 for (chan_id, chan) in by_id.iter_mut() {
7063                         if chan.outbound_scid_alias() == 0 {
7064                                 let mut outbound_scid_alias;
7065                                 loop {
7066                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
7067                                                 .get_fake_scid(best_block_height, &genesis_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.keys_manager);
7068                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
7069                                 }
7070                                 chan.set_outbound_scid_alias(outbound_scid_alias);
7071                         } else if !outbound_scid_aliases.insert(chan.outbound_scid_alias()) {
7072                                 // Note that in rare cases its possible to hit this while reading an older
7073                                 // channel if we just happened to pick a colliding outbound alias above.
7074                                 log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.outbound_scid_alias());
7075                                 return Err(DecodeError::InvalidValue);
7076                         }
7077                         if chan.is_usable() {
7078                                 if short_to_chan_info.insert(chan.outbound_scid_alias(), (chan.get_counterparty_node_id(), *chan_id)).is_some() {
7079                                         // Note that in rare cases its possible to hit this while reading an older
7080                                         // channel if we just happened to pick a colliding outbound alias above.
7081                                         log_error!(args.logger, "Got duplicate outbound SCID alias; {}", chan.outbound_scid_alias());
7082                                         return Err(DecodeError::InvalidValue);
7083                                 }
7084                         }
7085                 }
7086
7087                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
7088
7089                 for (_, monitor) in args.channel_monitors.iter() {
7090                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
7091                                 if let Some((payment_purpose, claimable_htlcs)) = claimable_htlcs.remove(&payment_hash) {
7092                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", log_bytes!(payment_hash.0));
7093                                         let mut claimable_amt_msat = 0;
7094                                         let mut receiver_node_id = Some(our_network_pubkey);
7095                                         let phantom_shared_secret = claimable_htlcs[0].prev_hop.phantom_shared_secret;
7096                                         if phantom_shared_secret.is_some() {
7097                                                 let phantom_pubkey = args.keys_manager.get_node_id(Recipient::PhantomNode)
7098                                                         .expect("Failed to get node_id for phantom node recipient");
7099                                                 receiver_node_id = Some(phantom_pubkey)
7100                                         }
7101                                         for claimable_htlc in claimable_htlcs {
7102                                                 claimable_amt_msat += claimable_htlc.value;
7103
7104                                                 // Add a holding-cell claim of the payment to the Channel, which should be
7105                                                 // applied ~immediately on peer reconnection. Because it won't generate a
7106                                                 // new commitment transaction we can just provide the payment preimage to
7107                                                 // the corresponding ChannelMonitor and nothing else.
7108                                                 //
7109                                                 // We do so directly instead of via the normal ChannelMonitor update
7110                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
7111                                                 // we're not allowed to call it directly yet. Further, we do the update
7112                                                 // without incrementing the ChannelMonitor update ID as there isn't any
7113                                                 // reason to.
7114                                                 // If we were to generate a new ChannelMonitor update ID here and then
7115                                                 // crash before the user finishes block connect we'd end up force-closing
7116                                                 // this channel as well. On the flip side, there's no harm in restarting
7117                                                 // without the new monitor persisted - we'll end up right back here on
7118                                                 // restart.
7119                                                 let previous_channel_id = claimable_htlc.prev_hop.outpoint.to_channel_id();
7120                                                 if let Some(channel) = by_id.get_mut(&previous_channel_id) {
7121                                                         channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &args.logger);
7122                                                 }
7123                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
7124                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
7125                                                 }
7126                                         }
7127                                         pending_events_read.push(events::Event::PaymentClaimed {
7128                                                 receiver_node_id,
7129                                                 payment_hash,
7130                                                 purpose: payment_purpose,
7131                                                 amount_msat: claimable_amt_msat,
7132                                         });
7133                                 }
7134                         }
7135                 }
7136
7137                 let channel_manager = ChannelManager {
7138                         genesis_hash,
7139                         fee_estimator: bounded_fee_estimator,
7140                         chain_monitor: args.chain_monitor,
7141                         tx_broadcaster: args.tx_broadcaster,
7142                         router: args.router,
7143
7144                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
7145
7146                         channel_state: Mutex::new(ChannelHolder {
7147                                 by_id,
7148                                 pending_msg_events: Vec::new(),
7149                         }),
7150                         inbound_payment_key: expanded_inbound_key,
7151                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
7152                         pending_outbound_payments: OutboundPayments { pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()) },
7153                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
7154
7155                         forward_htlcs: Mutex::new(forward_htlcs),
7156                         claimable_payments: Mutex::new(ClaimablePayments { claimable_htlcs, pending_claiming_payments: pending_claiming_payments.unwrap() }),
7157                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
7158                         id_to_peer: Mutex::new(id_to_peer),
7159                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
7160                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
7161
7162                         probing_cookie_secret: probing_cookie_secret.unwrap(),
7163
7164                         our_network_key,
7165                         our_network_pubkey,
7166                         secp_ctx,
7167
7168                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
7169
7170                         per_peer_state: RwLock::new(per_peer_state),
7171
7172                         pending_events: Mutex::new(pending_events_read),
7173                         pending_background_events: Mutex::new(pending_background_events_read),
7174                         total_consistency_lock: RwLock::new(()),
7175                         persistence_notifier: Notifier::new(),
7176
7177                         keys_manager: args.keys_manager,
7178                         logger: args.logger,
7179                         default_configuration: args.default_config,
7180                 };
7181
7182                 for htlc_source in failed_htlcs.drain(..) {
7183                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
7184                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
7185                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7186                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
7187                 }
7188
7189                 //TODO: Broadcast channel update for closed channels, but only after we've made a
7190                 //connection or two.
7191
7192                 Ok((best_block_hash.clone(), channel_manager))
7193         }
7194 }
7195
7196 #[cfg(test)]
7197 mod tests {
7198         use bitcoin::hashes::Hash;
7199         use bitcoin::hashes::sha256::Hash as Sha256;
7200         use core::time::Duration;
7201         use core::sync::atomic::Ordering;
7202         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
7203         use crate::ln::channelmanager::{self, inbound_payment, PaymentId, PaymentSendFailure};
7204         use crate::ln::functional_test_utils::*;
7205         use crate::ln::msgs;
7206         use crate::ln::msgs::ChannelMessageHandler;
7207         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
7208         use crate::util::errors::APIError;
7209         use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
7210         use crate::util::test_utils;
7211         use crate::chain::keysinterface::{EntropySource, KeysInterface};
7212
7213         #[test]
7214         fn test_notify_limits() {
7215                 // Check that a few cases which don't require the persistence of a new ChannelManager,
7216                 // indeed, do not cause the persistence of a new ChannelManager.
7217                 let chanmon_cfgs = create_chanmon_cfgs(3);
7218                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7219                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7220                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7221
7222                 // All nodes start with a persistable update pending as `create_network` connects each node
7223                 // with all other nodes to make most tests simpler.
7224                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7225                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7226                 assert!(nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7227
7228                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7229
7230                 // We check that the channel info nodes have doesn't change too early, even though we try
7231                 // to connect messages with new values
7232                 chan.0.contents.fee_base_msat *= 2;
7233                 chan.1.contents.fee_base_msat *= 2;
7234                 let node_a_chan_info = nodes[0].node.list_channels()[0].clone();
7235                 let node_b_chan_info = nodes[1].node.list_channels()[0].clone();
7236
7237                 // The first two nodes (which opened a channel) should now require fresh persistence
7238                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7239                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7240                 // ... but the last node should not.
7241                 assert!(!nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7242                 // After persisting the first two nodes they should no longer need fresh persistence.
7243                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7244                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7245
7246                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
7247                 // about the channel.
7248                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
7249                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
7250                 assert!(!nodes[2].node.await_persistable_update_timeout(Duration::from_millis(1)));
7251
7252                 // The nodes which are a party to the channel should also ignore messages from unrelated
7253                 // parties.
7254                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
7255                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
7256                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
7257                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
7258                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7259                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7260
7261                 // At this point the channel info given by peers should still be the same.
7262                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
7263                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
7264
7265                 // An earlier version of handle_channel_update didn't check the directionality of the
7266                 // update message and would always update the local fee info, even if our peer was
7267                 // (spuriously) forwarding us our own channel_update.
7268                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
7269                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
7270                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
7271
7272                 // First deliver each peers' own message, checking that the node doesn't need to be
7273                 // persisted and that its channel info remains the same.
7274                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
7275                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
7276                 assert!(!nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7277                 assert!(!nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7278                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
7279                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
7280
7281                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
7282                 // the channel info has updated.
7283                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
7284                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
7285                 assert!(nodes[0].node.await_persistable_update_timeout(Duration::from_millis(1)));
7286                 assert!(nodes[1].node.await_persistable_update_timeout(Duration::from_millis(1)));
7287                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
7288                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
7289         }
7290
7291         #[test]
7292         fn test_keysend_dup_hash_partial_mpp() {
7293                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
7294                 // expected.
7295                 let chanmon_cfgs = create_chanmon_cfgs(2);
7296                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7297                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7298                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7299                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7300
7301                 // First, send a partial MPP payment.
7302                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
7303                 let mut mpp_route = route.clone();
7304                 mpp_route.paths.push(mpp_route.paths[0].clone());
7305
7306                 let payment_id = PaymentId([42; 32]);
7307                 // Use the utility function send_payment_along_path to send the payment with MPP data which
7308                 // indicates there are more HTLCs coming.
7309                 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.
7310                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &mpp_route).unwrap();
7311                 nodes[0].node.send_payment_along_path(&mpp_route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
7312                 check_added_monitors!(nodes[0], 1);
7313                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7314                 assert_eq!(events.len(), 1);
7315                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
7316
7317                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
7318                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
7319                 check_added_monitors!(nodes[0], 1);
7320                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7321                 assert_eq!(events.len(), 1);
7322                 let ev = events.drain(..).next().unwrap();
7323                 let payment_event = SendEvent::from_event(ev);
7324                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7325                 check_added_monitors!(nodes[1], 0);
7326                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7327                 expect_pending_htlcs_forwardable!(nodes[1]);
7328                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7329                 check_added_monitors!(nodes[1], 1);
7330                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7331                 assert!(updates.update_add_htlcs.is_empty());
7332                 assert!(updates.update_fulfill_htlcs.is_empty());
7333                 assert_eq!(updates.update_fail_htlcs.len(), 1);
7334                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7335                 assert!(updates.update_fee.is_none());
7336                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7337                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
7338                 expect_payment_failed!(nodes[0], our_payment_hash, true);
7339
7340                 // Send the second half of the original MPP payment.
7341                 nodes[0].node.send_payment_along_path(&mpp_route.paths[1], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
7342                 check_added_monitors!(nodes[0], 1);
7343                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7344                 assert_eq!(events.len(), 1);
7345                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
7346
7347                 // Claim the full MPP payment. Note that we can't use a test utility like
7348                 // claim_funds_along_route because the ordering of the messages causes the second half of the
7349                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
7350                 // lightning messages manually.
7351                 nodes[1].node.claim_funds(payment_preimage);
7352                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
7353                 check_added_monitors!(nodes[1], 2);
7354
7355                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7356                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
7357                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
7358                 check_added_monitors!(nodes[0], 1);
7359                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7360                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
7361                 check_added_monitors!(nodes[1], 1);
7362                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7363                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
7364                 check_added_monitors!(nodes[1], 1);
7365                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7366                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
7367                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
7368                 check_added_monitors!(nodes[0], 1);
7369                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7370                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
7371                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7372                 check_added_monitors!(nodes[0], 1);
7373                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
7374                 check_added_monitors!(nodes[1], 1);
7375                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
7376                 check_added_monitors!(nodes[1], 1);
7377                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7378                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
7379                 check_added_monitors!(nodes[0], 1);
7380
7381                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
7382                 // path's success and a PaymentPathSuccessful event for each path's success.
7383                 let events = nodes[0].node.get_and_clear_pending_events();
7384                 assert_eq!(events.len(), 3);
7385                 match events[0] {
7386                         Event::PaymentSent { payment_id: ref id, payment_preimage: ref preimage, payment_hash: ref hash, .. } => {
7387                                 assert_eq!(Some(payment_id), *id);
7388                                 assert_eq!(payment_preimage, *preimage);
7389                                 assert_eq!(our_payment_hash, *hash);
7390                         },
7391                         _ => panic!("Unexpected event"),
7392                 }
7393                 match events[1] {
7394                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
7395                                 assert_eq!(payment_id, *actual_payment_id);
7396                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
7397                                 assert_eq!(route.paths[0], *path);
7398                         },
7399                         _ => panic!("Unexpected event"),
7400                 }
7401                 match events[2] {
7402                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
7403                                 assert_eq!(payment_id, *actual_payment_id);
7404                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
7405                                 assert_eq!(route.paths[0], *path);
7406                         },
7407                         _ => panic!("Unexpected event"),
7408                 }
7409         }
7410
7411         #[test]
7412         fn test_keysend_dup_payment_hash() {
7413                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
7414                 //      outbound regular payment fails as expected.
7415                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
7416                 //      fails as expected.
7417                 let chanmon_cfgs = create_chanmon_cfgs(2);
7418                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7419                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7420                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7421                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7422                 let scorer = test_utils::TestScorer::with_penalty(0);
7423                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7424
7425                 // To start (1), send a regular payment but don't claim it.
7426                 let expected_route = [&nodes[1]];
7427                 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &expected_route, 100_000);
7428
7429                 // Next, attempt a keysend payment and make sure it fails.
7430                 let route_params = RouteParameters {
7431                         payment_params: PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id()),
7432                         final_value_msat: 100_000,
7433                         final_cltv_expiry_delta: TEST_FINAL_CLTV,
7434                 };
7435                 let route = find_route(
7436                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
7437                         None, nodes[0].logger, &scorer, &random_seed_bytes
7438                 ).unwrap();
7439                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
7440                 check_added_monitors!(nodes[0], 1);
7441                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7442                 assert_eq!(events.len(), 1);
7443                 let ev = events.drain(..).next().unwrap();
7444                 let payment_event = SendEvent::from_event(ev);
7445                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7446                 check_added_monitors!(nodes[1], 0);
7447                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7448                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
7449                 // fails), the second will process the resulting failure and fail the HTLC backward
7450                 expect_pending_htlcs_forwardable!(nodes[1]);
7451                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
7452                 check_added_monitors!(nodes[1], 1);
7453                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7454                 assert!(updates.update_add_htlcs.is_empty());
7455                 assert!(updates.update_fulfill_htlcs.is_empty());
7456                 assert_eq!(updates.update_fail_htlcs.len(), 1);
7457                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7458                 assert!(updates.update_fee.is_none());
7459                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7460                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
7461                 expect_payment_failed!(nodes[0], payment_hash, true);
7462
7463                 // Finally, claim the original payment.
7464                 claim_payment(&nodes[0], &expected_route, payment_preimage);
7465
7466                 // To start (2), send a keysend payment but don't claim it.
7467                 let payment_preimage = PaymentPreimage([42; 32]);
7468                 let route = find_route(
7469                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
7470                         None, nodes[0].logger, &scorer, &random_seed_bytes
7471                 ).unwrap();
7472                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), PaymentId(payment_preimage.0)).unwrap();
7473                 check_added_monitors!(nodes[0], 1);
7474                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7475                 assert_eq!(events.len(), 1);
7476                 let event = events.pop().unwrap();
7477                 let path = vec![&nodes[1]];
7478                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
7479
7480                 // Next, attempt a regular payment and make sure it fails.
7481                 let payment_secret = PaymentSecret([43; 32]);
7482                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7483                 check_added_monitors!(nodes[0], 1);
7484                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7485                 assert_eq!(events.len(), 1);
7486                 let ev = events.drain(..).next().unwrap();
7487                 let payment_event = SendEvent::from_event(ev);
7488                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7489                 check_added_monitors!(nodes[1], 0);
7490                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7491                 expect_pending_htlcs_forwardable!(nodes[1]);
7492                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
7493                 check_added_monitors!(nodes[1], 1);
7494                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7495                 assert!(updates.update_add_htlcs.is_empty());
7496                 assert!(updates.update_fulfill_htlcs.is_empty());
7497                 assert_eq!(updates.update_fail_htlcs.len(), 1);
7498                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7499                 assert!(updates.update_fee.is_none());
7500                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7501                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
7502                 expect_payment_failed!(nodes[0], payment_hash, true);
7503
7504                 // Finally, succeed the keysend payment.
7505                 claim_payment(&nodes[0], &expected_route, payment_preimage);
7506         }
7507
7508         #[test]
7509         fn test_keysend_hash_mismatch() {
7510                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
7511                 // preimage doesn't match the msg's payment hash.
7512                 let chanmon_cfgs = create_chanmon_cfgs(2);
7513                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7514                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7515                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7516
7517                 let payer_pubkey = nodes[0].node.get_our_node_id();
7518                 let payee_pubkey = nodes[1].node.get_our_node_id();
7519                 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7520                 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7521
7522                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
7523                 let route_params = RouteParameters {
7524                         payment_params: PaymentParameters::for_keysend(payee_pubkey),
7525                         final_value_msat: 10_000,
7526                         final_cltv_expiry_delta: 40,
7527                 };
7528                 let network_graph = nodes[0].network_graph.clone();
7529                 let first_hops = nodes[0].node.list_usable_channels();
7530                 let scorer = test_utils::TestScorer::with_penalty(0);
7531                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7532                 let route = find_route(
7533                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
7534                         nodes[0].logger, &scorer, &random_seed_bytes
7535                 ).unwrap();
7536
7537                 let test_preimage = PaymentPreimage([42; 32]);
7538                 let mismatch_payment_hash = PaymentHash([43; 32]);
7539                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash, None, PaymentId(mismatch_payment_hash.0), &route).unwrap();
7540                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash, &None, Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
7541                 check_added_monitors!(nodes[0], 1);
7542
7543                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7544                 assert_eq!(updates.update_add_htlcs.len(), 1);
7545                 assert!(updates.update_fulfill_htlcs.is_empty());
7546                 assert!(updates.update_fail_htlcs.is_empty());
7547                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7548                 assert!(updates.update_fee.is_none());
7549                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7550
7551                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Payment preimage didn't match payment hash".to_string(), 1);
7552         }
7553
7554         #[test]
7555         fn test_keysend_msg_with_secret_err() {
7556                 // Test that we error as expected if we receive a keysend payment that includes a payment secret.
7557                 let chanmon_cfgs = create_chanmon_cfgs(2);
7558                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7559                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7560                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7561
7562                 let payer_pubkey = nodes[0].node.get_our_node_id();
7563                 let payee_pubkey = nodes[1].node.get_our_node_id();
7564                 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7565                 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7566
7567                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
7568                 let route_params = RouteParameters {
7569                         payment_params: PaymentParameters::for_keysend(payee_pubkey),
7570                         final_value_msat: 10_000,
7571                         final_cltv_expiry_delta: 40,
7572                 };
7573                 let network_graph = nodes[0].network_graph.clone();
7574                 let first_hops = nodes[0].node.list_usable_channels();
7575                 let scorer = test_utils::TestScorer::with_penalty(0);
7576                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7577                 let route = find_route(
7578                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
7579                         nodes[0].logger, &scorer, &random_seed_bytes
7580                 ).unwrap();
7581
7582                 let test_preimage = PaymentPreimage([42; 32]);
7583                 let test_secret = PaymentSecret([43; 32]);
7584                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).into_inner());
7585                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash, Some(test_secret), PaymentId(payment_hash.0), &route).unwrap();
7586                 nodes[0].node.test_send_payment_internal(&route, payment_hash, &Some(test_secret), Some(test_preimage), PaymentId(payment_hash.0), None, session_privs).unwrap();
7587                 check_added_monitors!(nodes[0], 1);
7588
7589                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7590                 assert_eq!(updates.update_add_htlcs.len(), 1);
7591                 assert!(updates.update_fulfill_htlcs.is_empty());
7592                 assert!(updates.update_fail_htlcs.is_empty());
7593                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7594                 assert!(updates.update_fee.is_none());
7595                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7596
7597                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "We don't support MPP keysend payments".to_string(), 1);
7598         }
7599
7600         #[test]
7601         fn test_multi_hop_missing_secret() {
7602                 let chanmon_cfgs = create_chanmon_cfgs(4);
7603                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7604                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7605                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7606
7607                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7608                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7609                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7610                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7611
7612                 // Marshall an MPP route.
7613                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7614                 let path = route.paths[0].clone();
7615                 route.paths.push(path);
7616                 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7617                 route.paths[0][0].short_channel_id = chan_1_id;
7618                 route.paths[0][1].short_channel_id = chan_3_id;
7619                 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7620                 route.paths[1][0].short_channel_id = chan_2_id;
7621                 route.paths[1][1].short_channel_id = chan_4_id;
7622
7623                 match nodes[0].node.send_payment(&route, payment_hash, &None, PaymentId(payment_hash.0)).unwrap_err() {
7624                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
7625                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))                        },
7626                         _ => panic!("unexpected error")
7627                 }
7628         }
7629
7630         #[test]
7631         fn bad_inbound_payment_hash() {
7632                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
7633                 let chanmon_cfgs = create_chanmon_cfgs(2);
7634                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7635                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7636                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7637
7638                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
7639                 let payment_data = msgs::FinalOnionHopData {
7640                         payment_secret,
7641                         total_msat: 100_000,
7642                 };
7643
7644                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
7645                 // payment verification fails as expected.
7646                 let mut bad_payment_hash = payment_hash.clone();
7647                 bad_payment_hash.0[0] += 1;
7648                 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) {
7649                         Ok(_) => panic!("Unexpected ok"),
7650                         Err(()) => {
7651                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment".to_string(), "Failing HTLC with user-generated payment_hash".to_string(), 1);
7652                         }
7653                 }
7654
7655                 // Check that using the original payment hash succeeds.
7656                 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());
7657         }
7658
7659         #[test]
7660         fn test_id_to_peer_coverage() {
7661                 // Test that the `ChannelManager:id_to_peer` contains channels which have been assigned
7662                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
7663                 // the channel is successfully closed.
7664                 let chanmon_cfgs = create_chanmon_cfgs(2);
7665                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7666                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7667                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7668
7669                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7670                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7671                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
7672                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7673                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
7674
7675                 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
7676                 let channel_id = &tx.txid().into_inner();
7677                 {
7678                         // Ensure that the `id_to_peer` map is empty until either party has received the
7679                         // funding transaction, and have the real `channel_id`.
7680                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
7681                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
7682                 }
7683
7684                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7685                 {
7686                         // Assert that `nodes[0]`'s `id_to_peer` map is populated with the channel as soon as
7687                         // as it has the funding transaction.
7688                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
7689                         assert_eq!(nodes_0_lock.len(), 1);
7690                         assert!(nodes_0_lock.contains_key(channel_id));
7691
7692                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
7693                 }
7694
7695                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7696
7697                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7698                 {
7699                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
7700                         assert_eq!(nodes_0_lock.len(), 1);
7701                         assert!(nodes_0_lock.contains_key(channel_id));
7702
7703                         // Assert that `nodes[1]`'s `id_to_peer` map is populated with the channel as soon as
7704                         // as it has the funding transaction.
7705                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
7706                         assert_eq!(nodes_1_lock.len(), 1);
7707                         assert!(nodes_1_lock.contains_key(channel_id));
7708                 }
7709                 check_added_monitors!(nodes[1], 1);
7710                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
7711                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
7712                 check_added_monitors!(nodes[0], 1);
7713                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
7714                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
7715                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
7716
7717                 nodes[0].node.close_channel(channel_id, &nodes[1].node.get_our_node_id()).unwrap();
7718                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id()));
7719                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7720                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &nodes_1_shutdown);
7721
7722                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
7723                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
7724                 {
7725                         // Assert that the channel is kept in the `id_to_peer` map for both nodes until the
7726                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
7727                         // fee for the closing transaction has been negotiated and the parties has the other
7728                         // party's signature for the fee negotiated closing transaction.)
7729                         let nodes_0_lock = nodes[0].node.id_to_peer.lock().unwrap();
7730                         assert_eq!(nodes_0_lock.len(), 1);
7731                         assert!(nodes_0_lock.contains_key(channel_id));
7732
7733                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
7734                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
7735                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
7736                         // kept in the `nodes[1]`'s `id_to_peer` map.
7737                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
7738                         assert_eq!(nodes_1_lock.len(), 1);
7739                         assert!(nodes_1_lock.contains_key(channel_id));
7740                 }
7741
7742                 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()));
7743                 {
7744                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
7745                         // therefore has all it needs to fully close the channel (both signatures for the
7746                         // closing transaction).
7747                         // Assert that the channel is removed from `nodes[0]`'s `id_to_peer` map as it can be
7748                         // fully closed by `nodes[0]`.
7749                         assert_eq!(nodes[0].node.id_to_peer.lock().unwrap().len(), 0);
7750
7751                         // Assert that the channel is still in `nodes[1]`'s  `id_to_peer` map, as `nodes[1]`
7752                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
7753                         let nodes_1_lock = nodes[1].node.id_to_peer.lock().unwrap();
7754                         assert_eq!(nodes_1_lock.len(), 1);
7755                         assert!(nodes_1_lock.contains_key(channel_id));
7756                 }
7757
7758                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
7759
7760                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
7761                 {
7762                         // Assert that the channel has now been removed from both parties `id_to_peer` map once
7763                         // they both have everything required to fully close the channel.
7764                         assert_eq!(nodes[1].node.id_to_peer.lock().unwrap().len(), 0);
7765                 }
7766                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
7767
7768                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
7769                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
7770         }
7771 }
7772
7773 #[cfg(all(any(test, feature = "_test_utils"), feature = "_bench_unstable"))]
7774 pub mod bench {
7775         use crate::chain::Listen;
7776         use crate::chain::chainmonitor::{ChainMonitor, Persist};
7777         use crate::chain::keysinterface::{EntropySource, KeysManager, KeysInterface, InMemorySigner};
7778         use crate::ln::channelmanager::{self, BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId};
7779         use crate::ln::functional_test_utils::*;
7780         use crate::ln::msgs::{ChannelMessageHandler, Init};
7781         use crate::routing::gossip::NetworkGraph;
7782         use crate::routing::router::{PaymentParameters, get_route};
7783         use crate::util::test_utils;
7784         use crate::util::config::UserConfig;
7785         use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
7786
7787         use bitcoin::hashes::Hash;
7788         use bitcoin::hashes::sha256::Hash as Sha256;
7789         use bitcoin::{Block, BlockHeader, PackedLockTime, Transaction, TxMerkleNode, TxOut};
7790
7791         use crate::sync::{Arc, Mutex};
7792
7793         use test::Bencher;
7794
7795         struct NodeHolder<'a, P: Persist<InMemorySigner>> {
7796                 node: &'a ChannelManager<
7797                         &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
7798                                 &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
7799                                 &'a test_utils::TestLogger, &'a P>,
7800                         &'a test_utils::TestBroadcaster, &'a KeysManager,
7801                         &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
7802                         &'a test_utils::TestLogger>,
7803         }
7804
7805         #[cfg(test)]
7806         #[bench]
7807         fn bench_sends(bench: &mut Bencher) {
7808                 bench_two_sends(bench, test_utils::TestPersister::new(), test_utils::TestPersister::new());
7809         }
7810
7811         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Bencher, persister_a: P, persister_b: P) {
7812                 // Do a simple benchmark of sending a payment back and forth between two nodes.
7813                 // Note that this is unrealistic as each payment send will require at least two fsync
7814                 // calls per node.
7815                 let network = bitcoin::Network::Testnet;
7816                 let genesis_hash = bitcoin::blockdata::constants::genesis_block(network).header.block_hash();
7817
7818                 let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7819                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7820                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
7821                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(genesis_hash, &logger_a)));
7822
7823                 let mut config: UserConfig = Default::default();
7824                 config.channel_handshake_config.minimum_depth = 1;
7825
7826                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
7827                 let seed_a = [1u8; 32];
7828                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
7829                 let node_a = ChannelManager::new(&fee_estimator, &chain_monitor_a, &tx_broadcaster, &router, &logger_a, &keys_manager_a, config.clone(), ChainParameters {
7830                         network,
7831                         best_block: BestBlock::from_genesis(network),
7832                 });
7833                 let node_a_holder = NodeHolder { node: &node_a };
7834
7835                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
7836                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
7837                 let seed_b = [2u8; 32];
7838                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
7839                 let node_b = ChannelManager::new(&fee_estimator, &chain_monitor_b, &tx_broadcaster, &router, &logger_b, &keys_manager_b, config.clone(), ChainParameters {
7840                         network,
7841                         best_block: BestBlock::from_genesis(network),
7842                 });
7843                 let node_b_holder = NodeHolder { node: &node_b };
7844
7845                 node_a.peer_connected(&node_b.get_our_node_id(), &Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7846                 node_b.peer_connected(&node_a.get_our_node_id(), &Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7847                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
7848                 node_b.handle_open_channel(&node_a.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(node_a_holder, MessageSendEvent::SendOpenChannel, node_b.get_our_node_id()));
7849                 node_a.handle_accept_channel(&node_b.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(node_b_holder, MessageSendEvent::SendAcceptChannel, node_a.get_our_node_id()));
7850
7851                 let tx;
7852                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
7853                         tx = Transaction { version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
7854                                 value: 8_000_000, script_pubkey: output_script,
7855                         }]};
7856                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
7857                 } else { panic!(); }
7858
7859                 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()));
7860                 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()));
7861
7862                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
7863
7864                 let block = Block {
7865                         header: BlockHeader { version: 0x20000000, prev_blockhash: genesis_hash, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
7866                         txdata: vec![tx],
7867                 };
7868                 Listen::block_connected(&node_a, &block, 1);
7869                 Listen::block_connected(&node_b, &block, 1);
7870
7871                 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()));
7872                 let msg_events = node_a.get_and_clear_pending_msg_events();
7873                 assert_eq!(msg_events.len(), 2);
7874                 match msg_events[0] {
7875                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
7876                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
7877                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
7878                         },
7879                         _ => panic!(),
7880                 }
7881                 match msg_events[1] {
7882                         MessageSendEvent::SendChannelUpdate { .. } => {},
7883                         _ => panic!(),
7884                 }
7885
7886                 let events_a = node_a.get_and_clear_pending_events();
7887                 assert_eq!(events_a.len(), 1);
7888                 match events_a[0] {
7889                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
7890                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
7891                         },
7892                         _ => panic!("Unexpected event"),
7893                 }
7894
7895                 let events_b = node_b.get_and_clear_pending_events();
7896                 assert_eq!(events_b.len(), 1);
7897                 match events_b[0] {
7898                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
7899                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
7900                         },
7901                         _ => panic!("Unexpected event"),
7902                 }
7903
7904                 let dummy_graph = NetworkGraph::new(genesis_hash, &logger_a);
7905
7906                 let mut payment_count: u64 = 0;
7907                 macro_rules! send_payment {
7908                         ($node_a: expr, $node_b: expr) => {
7909                                 let usable_channels = $node_a.list_usable_channels();
7910                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id())
7911                                         .with_features(channelmanager::provided_invoice_features());
7912                                 let scorer = test_utils::TestScorer::with_penalty(0);
7913                                 let seed = [3u8; 32];
7914                                 let keys_manager = KeysManager::new(&seed, 42, 42);
7915                                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7916                                 let route = get_route(&$node_a.get_our_node_id(), &payment_params, &dummy_graph.read_only(),
7917                                         Some(&usable_channels.iter().map(|r| r).collect::<Vec<_>>()), 10_000, TEST_FINAL_CLTV, &logger_a, &scorer, &random_seed_bytes).unwrap();
7918
7919                                 let mut payment_preimage = PaymentPreimage([0; 32]);
7920                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
7921                                 payment_count += 1;
7922                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
7923                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
7924
7925                                 $node_a.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7926                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
7927                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
7928                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
7929                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_b }, $node_a.get_our_node_id());
7930                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
7931                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
7932                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_a }, MessageSendEvent::SendRevokeAndACK, $node_b.get_our_node_id()));
7933
7934                                 expect_pending_htlcs_forwardable!(NodeHolder { node: &$node_b });
7935                                 expect_payment_claimable!(NodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
7936                                 $node_b.claim_funds(payment_preimage);
7937                                 expect_payment_claimed!(NodeHolder { node: &$node_b }, payment_hash, 10_000);
7938
7939                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
7940                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
7941                                                 assert_eq!(node_id, $node_a.get_our_node_id());
7942                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7943                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
7944                                         },
7945                                         _ => panic!("Failed to generate claim event"),
7946                                 }
7947
7948                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_a }, $node_b.get_our_node_id());
7949                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
7950                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
7951                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &get_event_msg!(NodeHolder { node: &$node_b }, MessageSendEvent::SendRevokeAndACK, $node_a.get_our_node_id()));
7952
7953                                 expect_payment_sent!(NodeHolder { node: &$node_a }, payment_preimage);
7954                         }
7955                 }
7956
7957                 bench.iter(|| {
7958                         send_payment!(node_a, node_b);
7959                         send_payment!(node_b, node_a);
7960                 });
7961         }
7962 }