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