848846b8c469647bd878cc30468e338c0b1476d0
[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 routing::router::get_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
21 use bitcoin::blockdata::block::{Block, BlockHeader};
22 use bitcoin::blockdata::constants::genesis_block;
23 use bitcoin::network::constants::Network;
24
25 use bitcoin::hashes::{Hash, HashEngine};
26 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29 use bitcoin::hashes::cmp::fixed_time_eq;
30 use bitcoin::hash_types::BlockHash;
31
32 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
33 use bitcoin::secp256k1::Secp256k1;
34 use bitcoin::secp256k1::ecdh::SharedSecret;
35 use bitcoin::secp256k1;
36
37 use chain;
38 use chain::Watch;
39 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
40 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
41 use 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 pub use ln::channel::CounterpartyForwardingInfo;
45 use ln::channel::{Channel, ChannelError};
46 use ln::features::{InitFeatures, NodeFeatures};
47 use routing::router::{Route, RouteHop};
48 use ln::msgs;
49 use ln::msgs::NetAddress;
50 use ln::onion_utils;
51 use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, OptionalField};
52 use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner};
53 use util::config::UserConfig;
54 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
55 use util::{byte_utils, events};
56 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writeable, Writer};
57 use util::chacha20::{ChaCha20, ChaChaReader};
58 use util::logger::Logger;
59 use util::errors::APIError;
60
61 use std::{cmp, mem};
62 use std::collections::{HashMap, hash_map, HashSet};
63 use std::io::{Cursor, Read};
64 use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
65 use std::sync::atomic::{AtomicUsize, Ordering};
66 use std::time::Duration;
67 #[cfg(any(test, feature = "allow_wallclock_use"))]
68 use std::time::Instant;
69 use std::marker::{Sync, Send};
70 use std::ops::Deref;
71 use bitcoin::hashes::hex::ToHex;
72
73 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
74 //
75 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
76 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
77 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
78 //
79 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
80 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
81 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
82 // before we forward it.
83 //
84 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
85 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
86 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
87 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
88 // our payment, which we can use to decode errors or inform the user that the payment was sent.
89
90 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
91 enum PendingHTLCRouting {
92         Forward {
93                 onion_packet: msgs::OnionPacket,
94                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
95         },
96         Receive {
97                 payment_data: Option<msgs::FinalOnionHopData>,
98                 incoming_cltv_expiry: u32, // Used to track when we should expire pending HTLCs that go unclaimed
99         },
100 }
101
102 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
103 pub(super) struct PendingHTLCInfo {
104         routing: PendingHTLCRouting,
105         incoming_shared_secret: [u8; 32],
106         payment_hash: PaymentHash,
107         pub(super) amt_to_forward: u64,
108         pub(super) outgoing_cltv_value: u32,
109 }
110
111 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
112 pub(super) enum HTLCFailureMsg {
113         Relay(msgs::UpdateFailHTLC),
114         Malformed(msgs::UpdateFailMalformedHTLC),
115 }
116
117 /// Stores whether we can't forward an HTLC or relevant forwarding info
118 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
119 pub(super) enum PendingHTLCStatus {
120         Forward(PendingHTLCInfo),
121         Fail(HTLCFailureMsg),
122 }
123
124 pub(super) enum HTLCForwardInfo {
125         AddHTLC {
126                 forward_info: PendingHTLCInfo,
127
128                 // These fields are produced in `forward_htlcs()` and consumed in
129                 // `process_pending_htlc_forwards()` for constructing the
130                 // `HTLCSource::PreviousHopData` for failed and forwarded
131                 // HTLCs.
132                 prev_short_channel_id: u64,
133                 prev_htlc_id: u64,
134                 prev_funding_outpoint: OutPoint,
135         },
136         FailHTLC {
137                 htlc_id: u64,
138                 err_packet: msgs::OnionErrorPacket,
139         },
140 }
141
142 /// Tracks the inbound corresponding to an outbound HTLC
143 #[derive(Clone, PartialEq)]
144 pub(crate) struct HTLCPreviousHopData {
145         short_channel_id: u64,
146         htlc_id: u64,
147         incoming_packet_shared_secret: [u8; 32],
148
149         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
150         // channel with a preimage provided by the forward channel.
151         outpoint: OutPoint,
152 }
153
154 struct ClaimableHTLC {
155         prev_hop: HTLCPreviousHopData,
156         value: u64,
157         /// Filled in when the HTLC was received with a payment_secret packet, which contains a
158         /// total_msat (which may differ from value if this is a Multi-Path Payment) and a
159         /// payment_secret which prevents path-probing attacks and can associate different HTLCs which
160         /// are part of the same payment.
161         payment_data: Option<msgs::FinalOnionHopData>,
162         cltv_expiry: u32,
163 }
164
165 /// Tracks the inbound corresponding to an outbound HTLC
166 #[derive(Clone, PartialEq)]
167 pub(crate) enum HTLCSource {
168         PreviousHopData(HTLCPreviousHopData),
169         OutboundRoute {
170                 path: Vec<RouteHop>,
171                 session_priv: SecretKey,
172                 /// Technically we can recalculate this from the route, but we cache it here to avoid
173                 /// doing a double-pass on route when we get a failure back
174                 first_hop_htlc_msat: u64,
175         },
176 }
177 #[cfg(test)]
178 impl HTLCSource {
179         pub fn dummy() -> Self {
180                 HTLCSource::OutboundRoute {
181                         path: Vec::new(),
182                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
183                         first_hop_htlc_msat: 0,
184                 }
185         }
186 }
187
188 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
189 pub(super) enum HTLCFailReason {
190         LightningError {
191                 err: msgs::OnionErrorPacket,
192         },
193         Reason {
194                 failure_code: u16,
195                 data: Vec<u8>,
196         }
197 }
198
199 /// payment_hash type, use to cross-lock hop
200 /// (C-not exported) as we just use [u8; 32] directly
201 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
202 pub struct PaymentHash(pub [u8;32]);
203 /// payment_preimage type, use to route payment between hop
204 /// (C-not exported) as we just use [u8; 32] directly
205 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
206 pub struct PaymentPreimage(pub [u8;32]);
207 /// payment_secret type, use to authenticate sender to the receiver and tie MPP HTLCs together
208 /// (C-not exported) as we just use [u8; 32] directly
209 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
210 pub struct PaymentSecret(pub [u8;32]);
211
212 type ShutdownResult = (Option<(OutPoint, ChannelMonitorUpdate)>, Vec<(HTLCSource, PaymentHash)>);
213
214 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
215 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
216 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
217 /// channel_state lock. We then return the set of things that need to be done outside the lock in
218 /// this struct and call handle_error!() on it.
219
220 struct MsgHandleErrInternal {
221         err: msgs::LightningError,
222         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
223 }
224 impl MsgHandleErrInternal {
225         #[inline]
226         fn send_err_msg_no_close(err: String, channel_id: [u8; 32]) -> Self {
227                 Self {
228                         err: LightningError {
229                                 err: err.clone(),
230                                 action: msgs::ErrorAction::SendErrorMessage {
231                                         msg: msgs::ErrorMessage {
232                                                 channel_id,
233                                                 data: err
234                                         },
235                                 },
236                         },
237                         shutdown_finish: None,
238                 }
239         }
240         #[inline]
241         fn ignore_no_close(err: String) -> Self {
242                 Self {
243                         err: LightningError {
244                                 err,
245                                 action: msgs::ErrorAction::IgnoreError,
246                         },
247                         shutdown_finish: None,
248                 }
249         }
250         #[inline]
251         fn from_no_close(err: msgs::LightningError) -> Self {
252                 Self { err, shutdown_finish: None }
253         }
254         #[inline]
255         fn from_finish_shutdown(err: String, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
256                 Self {
257                         err: LightningError {
258                                 err: err.clone(),
259                                 action: msgs::ErrorAction::SendErrorMessage {
260                                         msg: msgs::ErrorMessage {
261                                                 channel_id,
262                                                 data: err
263                                         },
264                                 },
265                         },
266                         shutdown_finish: Some((shutdown_res, channel_update)),
267                 }
268         }
269         #[inline]
270         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
271                 Self {
272                         err: match err {
273                                 ChannelError::Ignore(msg) => LightningError {
274                                         err: msg,
275                                         action: msgs::ErrorAction::IgnoreError,
276                                 },
277                                 ChannelError::Close(msg) => LightningError {
278                                         err: msg.clone(),
279                                         action: msgs::ErrorAction::SendErrorMessage {
280                                                 msg: msgs::ErrorMessage {
281                                                         channel_id,
282                                                         data: msg
283                                                 },
284                                         },
285                                 },
286                                 ChannelError::CloseDelayBroadcast(msg) => LightningError {
287                                         err: msg.clone(),
288                                         action: msgs::ErrorAction::SendErrorMessage {
289                                                 msg: msgs::ErrorMessage {
290                                                         channel_id,
291                                                         data: msg
292                                                 },
293                                         },
294                                 },
295                         },
296                         shutdown_finish: None,
297                 }
298         }
299 }
300
301 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
302 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
303 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
304 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
305 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
306
307 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
308 /// be sent in the order they appear in the return value, however sometimes the order needs to be
309 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
310 /// they were originally sent). In those cases, this enum is also returned.
311 #[derive(Clone, PartialEq)]
312 pub(super) enum RAACommitmentOrder {
313         /// Send the CommitmentUpdate messages first
314         CommitmentFirst,
315         /// Send the RevokeAndACK message first
316         RevokeAndACKFirst,
317 }
318
319 // Note this is only exposed in cfg(test):
320 pub(super) struct ChannelHolder<Signer: Sign> {
321         pub(super) by_id: HashMap<[u8; 32], Channel<Signer>>,
322         pub(super) short_to_id: HashMap<u64, [u8; 32]>,
323         /// short channel id -> forward infos. Key of 0 means payments received
324         /// Note that while this is held in the same mutex as the channels themselves, no consistency
325         /// guarantees are made about the existence of a channel with the short id here, nor the short
326         /// ids in the PendingHTLCInfo!
327         pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
328         /// (payment_hash, payment_secret) -> Vec<HTLCs> for tracking HTLCs that
329         /// were to us and can be failed/claimed by the user
330         /// Note that while this is held in the same mutex as the channels themselves, no consistency
331         /// guarantees are made about the channels given here actually existing anymore by the time you
332         /// go to read them!
333         claimable_htlcs: HashMap<(PaymentHash, Option<PaymentSecret>), Vec<ClaimableHTLC>>,
334         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
335         /// for broadcast messages, where ordering isn't as strict).
336         pub(super) pending_msg_events: Vec<MessageSendEvent>,
337 }
338
339 /// Events which we process internally but cannot be procsesed immediately at the generation site
340 /// for some reason. They are handled in timer_chan_freshness_every_min, so may be processed with
341 /// quite some time lag.
342 enum BackgroundEvent {
343         /// Handle a ChannelMonitorUpdate that closes a channel, broadcasting its current latest holder
344         /// commitment transaction.
345         ClosingMonitorUpdate((OutPoint, ChannelMonitorUpdate)),
346 }
347
348 /// State we hold per-peer. In the future we should put channels in here, but for now we only hold
349 /// the latest Init features we heard from the peer.
350 struct PeerState {
351         latest_features: InitFeatures,
352 }
353
354 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
355 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
356
357 /// SimpleArcChannelManager is useful when you need a ChannelManager with a static lifetime, e.g.
358 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
359 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
360 /// SimpleRefChannelManager is the more appropriate type. Defining these type aliases prevents
361 /// issues such as overly long function definitions. Note that the ChannelManager can take any
362 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
363 /// concrete type of the KeysManager.
364 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<InMemorySigner, Arc<M>, Arc<T>, Arc<KeysManager>, Arc<F>, Arc<L>>;
365
366 /// SimpleRefChannelManager is a type alias for a ChannelManager reference, and is the reference
367 /// counterpart to the SimpleArcChannelManager type alias. Use this type by default when you don't
368 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
369 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
370 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
371 /// helps with issues such as long function definitions. Note that the ChannelManager can take any
372 /// type that implements KeysInterface for its keys manager, but this type alias chooses the
373 /// concrete type of the KeysManager.
374 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManager<InMemorySigner, &'a M, &'b T, &'c KeysManager, &'d F, &'e L>;
375
376 /// Manager which keeps track of a number of channels and sends messages to the appropriate
377 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
378 ///
379 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
380 /// to individual Channels.
381 ///
382 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
383 /// all peers during write/read (though does not modify this instance, only the instance being
384 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
385 /// called funding_transaction_generated for outbound channels).
386 ///
387 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
388 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
389 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
390 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
391 /// the serialization process). If the deserialized version is out-of-date compared to the
392 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
393 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
394 ///
395 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
396 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
397 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
398 /// block_connected() to step towards your best block) upon deserialization before using the
399 /// object!
400 ///
401 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
402 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
403 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
404 /// offline for a full minute. In order to track this, you must call
405 /// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
406 ///
407 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
408 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
409 /// essentially you should default to using a SimpleRefChannelManager, and use a
410 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
411 /// you're using lightning-net-tokio.
412 pub struct ChannelManager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
413         where M::Target: chain::Watch<Signer>,
414         T::Target: BroadcasterInterface,
415         K::Target: KeysInterface<Signer = Signer>,
416         F::Target: FeeEstimator,
417                                 L::Target: Logger,
418 {
419         default_configuration: UserConfig,
420         genesis_hash: BlockHash,
421         fee_estimator: F,
422         chain_monitor: M,
423         tx_broadcaster: T,
424
425         #[cfg(test)]
426         pub(super) latest_block_height: AtomicUsize,
427         #[cfg(not(test))]
428         latest_block_height: AtomicUsize,
429         last_block_hash: RwLock<BlockHash>,
430         secp_ctx: Secp256k1<secp256k1::All>,
431
432         #[cfg(any(test, feature = "_test_utils"))]
433         pub(super) channel_state: Mutex<ChannelHolder<Signer>>,
434         #[cfg(not(any(test, feature = "_test_utils")))]
435         channel_state: Mutex<ChannelHolder<Signer>>,
436         our_network_key: SecretKey,
437         our_network_pubkey: PublicKey,
438
439         /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
440         /// value increases strictly since we don't assume access to a time source.
441         last_node_announcement_serial: AtomicUsize,
442
443         /// The bulk of our storage will eventually be here (channels and message queues and the like).
444         /// If we are connected to a peer we always at least have an entry here, even if no channels
445         /// are currently open with that peer.
446         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
447         /// operate on the inner value freely. Sadly, this prevents parallel operation when opening a
448         /// new channel.
449         per_peer_state: RwLock<HashMap<PublicKey, Mutex<PeerState>>>,
450
451         pending_events: Mutex<Vec<events::Event>>,
452         pending_background_events: Mutex<Vec<BackgroundEvent>>,
453         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
454         /// Essentially just when we're serializing ourselves out.
455         /// Taken first everywhere where we are making changes before any other locks.
456         /// When acquiring this lock in read mode, rather than acquiring it directly, call
457         /// `PersistenceNotifierGuard::new(..)` and pass the lock to it, to ensure the PersistenceNotifier
458         /// the lock contains sends out a notification when the lock is released.
459         total_consistency_lock: RwLock<()>,
460
461         persistence_notifier: PersistenceNotifier,
462
463         keys_manager: K,
464
465         logger: L,
466 }
467
468 /// Chain-related parameters used to construct a new `ChannelManager`.
469 ///
470 /// Typically, the block-specific parameters are derived from the best block hash for the network,
471 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
472 /// are not needed when deserializing a previously constructed `ChannelManager`.
473 pub struct ChainParameters {
474         /// The network for determining the `chain_hash` in Lightning messages.
475         pub network: Network,
476
477         /// The hash of the latest block successfully connected.
478         pub latest_hash: BlockHash,
479
480         /// The height of the latest block successfully connected.
481         ///
482         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
483         pub latest_height: usize,
484 }
485
486 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
487 /// desirable to notify any listeners on `await_persistable_update_timeout`/
488 /// `await_persistable_update` that new updates are available for persistence. Therefore, this
489 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
490 /// sending the aforementioned notification (since the lock being released indicates that the
491 /// updates are ready for persistence).
492 struct PersistenceNotifierGuard<'a> {
493         persistence_notifier: &'a PersistenceNotifier,
494         // We hold onto this result so the lock doesn't get released immediately.
495         _read_guard: RwLockReadGuard<'a, ()>,
496 }
497
498 impl<'a> PersistenceNotifierGuard<'a> {
499         fn new(lock: &'a RwLock<()>, notifier: &'a PersistenceNotifier) -> Self {
500                 let read_guard = lock.read().unwrap();
501
502                 Self {
503                         persistence_notifier: notifier,
504                         _read_guard: read_guard,
505                 }
506         }
507 }
508
509 impl<'a> Drop for PersistenceNotifierGuard<'a> {
510         fn drop(&mut self) {
511                 self.persistence_notifier.notify();
512         }
513 }
514
515 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
516 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
517 ///
518 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
519 ///
520 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
521 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
522 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
523 /// the maximum required amount in lnd as of March 2021.
524 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
525
526 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
527 /// HTLC's CLTV. The current default represents roughly six hours of blocks at six blocks/hour.
528 ///
529 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
530 ///
531 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
532 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
533 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
534 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
535 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
536 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6 * 6;
537 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
538
539 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
540 // ie that if the next-hop peer fails the HTLC within
541 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
542 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
543 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
544 // LATENCY_GRACE_PERIOD_BLOCKS.
545 #[deny(const_err)]
546 #[allow(dead_code)]
547 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;
548
549 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
550 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
551 #[deny(const_err)]
552 #[allow(dead_code)]
553 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
554
555 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
556 #[derive(Clone)]
557 pub struct ChannelDetails {
558         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
559         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
560         /// Note that this means this value is *not* persistent - it can change once during the
561         /// lifetime of the channel.
562         pub channel_id: [u8; 32],
563         /// The position of the funding transaction in the chain. None if the funding transaction has
564         /// not yet been confirmed and the channel fully opened.
565         pub short_channel_id: Option<u64>,
566         /// The node_id of our counterparty
567         pub remote_network_id: PublicKey,
568         /// The Features the channel counterparty provided upon last connection.
569         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
570         /// many routing-relevant features are present in the init context.
571         pub counterparty_features: InitFeatures,
572         /// The value, in satoshis, of this channel as appears in the funding output
573         pub channel_value_satoshis: u64,
574         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
575         pub user_id: u64,
576         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
577         /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
578         /// available for inclusion in new outbound HTLCs). This further does not include any pending
579         /// outgoing HTLCs which are awaiting some other resolution to be sent.
580         pub outbound_capacity_msat: u64,
581         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
582         /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
583         /// available for inclusion in new inbound HTLCs).
584         /// Note that there are some corner cases not fully handled here, so the actual available
585         /// inbound capacity may be slightly higher than this.
586         pub inbound_capacity_msat: u64,
587         /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
588         /// the peer is connected, and (c) no monitor update failure is pending resolution.
589         pub is_live: bool,
590
591         /// Information on the fees and requirements that the counterparty requires when forwarding
592         /// payments to us through this channel.
593         pub counterparty_forwarding_info: Option<CounterpartyForwardingInfo>,
594 }
595
596 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
597 /// Err() type describing which state the payment is in, see the description of individual enum
598 /// states for more.
599 #[derive(Clone, Debug)]
600 pub enum PaymentSendFailure {
601         /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
602         /// send the payment at all. No channel state has been changed or messages sent to peers, and
603         /// once you've changed the parameter at error, you can freely retry the payment in full.
604         ParameterError(APIError),
605         /// A parameter in a single path which was passed to send_payment was invalid, preventing us
606         /// from attempting to send the payment at all. No channel state has been changed or messages
607         /// sent to peers, and once you've changed the parameter at error, you can freely retry the
608         /// payment in full.
609         ///
610         /// The results here are ordered the same as the paths in the route object which was passed to
611         /// send_payment.
612         PathParameterError(Vec<Result<(), APIError>>),
613         /// All paths which were attempted failed to send, with no channel state change taking place.
614         /// You can freely retry the payment in full (though you probably want to do so over different
615         /// paths than the ones selected).
616         AllFailedRetrySafe(Vec<APIError>),
617         /// Some paths which were attempted failed to send, though possibly not all. At least some
618         /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
619         /// in over-/re-payment.
620         ///
621         /// The results here are ordered the same as the paths in the route object which was passed to
622         /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
623         /// retried (though there is currently no API with which to do so).
624         ///
625         /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
626         /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
627         /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
628         /// with the latest update_id.
629         PartialFailure(Vec<Result<(), APIError>>),
630 }
631
632 macro_rules! handle_error {
633         ($self: ident, $internal: expr, $counterparty_node_id: expr) => {
634                 match $internal {
635                         Ok(msg) => Ok(msg),
636                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
637                                 #[cfg(debug_assertions)]
638                                 {
639                                         // In testing, ensure there are no deadlocks where the lock is already held upon
640                                         // entering the macro.
641                                         assert!($self.channel_state.try_lock().is_ok());
642                                 }
643
644                                 let mut msg_events = Vec::with_capacity(2);
645
646                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
647                                         $self.finish_force_close_channel(shutdown_res);
648                                         if let Some(update) = update_option {
649                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
650                                                         msg: update
651                                                 });
652                                         }
653                                 }
654
655                                 log_error!($self.logger, "{}", err.err);
656                                 if let msgs::ErrorAction::IgnoreError = err.action {
657                                 } else {
658                                         msg_events.push(events::MessageSendEvent::HandleError {
659                                                 node_id: $counterparty_node_id,
660                                                 action: err.action.clone()
661                                         });
662                                 }
663
664                                 if !msg_events.is_empty() {
665                                         $self.channel_state.lock().unwrap().pending_msg_events.append(&mut msg_events);
666                                 }
667
668                                 // Return error in case higher-API need one
669                                 Err(err)
670                         },
671                 }
672         }
673 }
674
675 macro_rules! break_chan_entry {
676         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
677                 match $res {
678                         Ok(res) => res,
679                         Err(ChannelError::Ignore(msg)) => {
680                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
681                         },
682                         Err(ChannelError::Close(msg)) => {
683                                 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
684                                 let (channel_id, mut chan) = $entry.remove_entry();
685                                 if let Some(short_id) = chan.get_short_channel_id() {
686                                         $channel_state.short_to_id.remove(&short_id);
687                                 }
688                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
689                         },
690                         Err(ChannelError::CloseDelayBroadcast(_)) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
691                 }
692         }
693 }
694
695 macro_rules! try_chan_entry {
696         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
697                 match $res {
698                         Ok(res) => res,
699                         Err(ChannelError::Ignore(msg)) => {
700                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
701                         },
702                         Err(ChannelError::Close(msg)) => {
703                                 log_trace!($self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
704                                 let (channel_id, mut chan) = $entry.remove_entry();
705                                 if let Some(short_id) = chan.get_short_channel_id() {
706                                         $channel_state.short_to_id.remove(&short_id);
707                                 }
708                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()))
709                         },
710                         Err(ChannelError::CloseDelayBroadcast(msg)) => {
711                                 log_error!($self.logger, "Channel {} need to be shutdown but closing transactions not broadcast due to {}", log_bytes!($entry.key()[..]), msg);
712                                 let (channel_id, mut chan) = $entry.remove_entry();
713                                 if let Some(short_id) = chan.get_short_channel_id() {
714                                         $channel_state.short_to_id.remove(&short_id);
715                                 }
716                                 let shutdown_res = chan.force_shutdown(false);
717                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, $self.get_channel_update(&chan).ok()))
718                         }
719                 }
720         }
721 }
722
723 macro_rules! handle_monitor_err {
724         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
725                 handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
726         };
727         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
728                 match $err {
729                         ChannelMonitorUpdateErr::PermanentFailure => {
730                                 log_error!($self.logger, "Closing channel {} due to monitor update PermanentFailure", log_bytes!($entry.key()[..]));
731                                 let (channel_id, mut chan) = $entry.remove_entry();
732                                 if let Some(short_id) = chan.get_short_channel_id() {
733                                         $channel_state.short_to_id.remove(&short_id);
734                                 }
735                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
736                                 // chain in a confused state! We need to move them into the ChannelMonitor which
737                                 // will be responsible for failing backwards once things confirm on-chain.
738                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
739                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
740                                 // us bother trying to claim it just to forward on to another peer. If we're
741                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
742                                 // given up the preimage yet, so might as well just wait until the payment is
743                                 // retried, avoiding the on-chain fees.
744                                 let res: Result<(), _> = Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure".to_owned(), channel_id, chan.force_shutdown(true), $self.get_channel_update(&chan).ok()));
745                                 res
746                         },
747                         ChannelMonitorUpdateErr::TemporaryFailure => {
748                                 log_info!($self.logger, "Disabling channel {} due to monitor update TemporaryFailure. On restore will send {} and process {} forwards and {} fails",
749                                                 log_bytes!($entry.key()[..]),
750                                                 if $resend_commitment && $resend_raa {
751                                                                 match $action_type {
752                                                                         RAACommitmentOrder::CommitmentFirst => { "commitment then RAA" },
753                                                                         RAACommitmentOrder::RevokeAndACKFirst => { "RAA then commitment" },
754                                                                 }
755                                                         } else if $resend_commitment { "commitment" }
756                                                         else if $resend_raa { "RAA" }
757                                                         else { "nothing" },
758                                                 (&$failed_forwards as &Vec<(PendingHTLCInfo, u64)>).len(),
759                                                 (&$failed_fails as &Vec<(HTLCSource, PaymentHash, HTLCFailReason)>).len());
760                                 if !$resend_commitment {
761                                         debug_assert!($action_type == RAACommitmentOrder::RevokeAndACKFirst || !$resend_raa);
762                                 }
763                                 if !$resend_raa {
764                                         debug_assert!($action_type == RAACommitmentOrder::CommitmentFirst || !$resend_commitment);
765                                 }
766                                 $entry.get_mut().monitor_update_failed($resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
767                                 Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor".to_owned()), *$entry.key()))
768                         },
769                 }
770         }
771 }
772
773 macro_rules! return_monitor_err {
774         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
775                 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment);
776         };
777         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
778                 return handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
779         }
780 }
781
782 // Does not break in case of TemporaryFailure!
783 macro_rules! maybe_break_monitor_err {
784         ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
785                 match (handle_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment), $err) {
786                         (e, ChannelMonitorUpdateErr::PermanentFailure) => {
787                                 break e;
788                         },
789                         (_, ChannelMonitorUpdateErr::TemporaryFailure) => { },
790                 }
791         }
792 }
793
794 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
795         where M::Target: chain::Watch<Signer>,
796         T::Target: BroadcasterInterface,
797         K::Target: KeysInterface<Signer = Signer>,
798         F::Target: FeeEstimator,
799         L::Target: Logger,
800 {
801         /// Constructs a new ChannelManager to hold several channels and route between them.
802         ///
803         /// This is the main "logic hub" for all channel-related actions, and implements
804         /// ChannelMessageHandler.
805         ///
806         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
807         ///
808         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
809         ///
810         /// Users need to notify the new ChannelManager when a new block is connected or
811         /// disconnected using its `block_connected` and `block_disconnected` methods, starting
812         /// from after `params.latest_hash`.
813         pub fn new(fee_est: F, chain_monitor: M, tx_broadcaster: T, logger: L, keys_manager: K, config: UserConfig, params: ChainParameters) -> Self {
814                 let mut secp_ctx = Secp256k1::new();
815                 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
816
817                 ChannelManager {
818                         default_configuration: config.clone(),
819                         genesis_hash: genesis_block(params.network).header.block_hash(),
820                         fee_estimator: fee_est,
821                         chain_monitor,
822                         tx_broadcaster,
823
824                         latest_block_height: AtomicUsize::new(params.latest_height),
825                         last_block_hash: RwLock::new(params.latest_hash),
826
827                         channel_state: Mutex::new(ChannelHolder{
828                                 by_id: HashMap::new(),
829                                 short_to_id: HashMap::new(),
830                                 forward_htlcs: HashMap::new(),
831                                 claimable_htlcs: HashMap::new(),
832                                 pending_msg_events: Vec::new(),
833                         }),
834                         our_network_key: keys_manager.get_node_secret(),
835                         our_network_pubkey: PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()),
836                         secp_ctx,
837
838                         last_node_announcement_serial: AtomicUsize::new(0),
839
840                         per_peer_state: RwLock::new(HashMap::new()),
841
842                         pending_events: Mutex::new(Vec::new()),
843                         pending_background_events: Mutex::new(Vec::new()),
844                         total_consistency_lock: RwLock::new(()),
845                         persistence_notifier: PersistenceNotifier::new(),
846
847                         keys_manager,
848
849                         logger,
850                 }
851         }
852
853         /// Creates a new outbound channel to the given remote node and with the given value.
854         ///
855         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
856         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
857         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
858         /// may wish to avoid using 0 for user_id here.
859         ///
860         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
861         /// PeerManager::process_events afterwards.
862         ///
863         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
864         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
865         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64, override_config: Option<UserConfig>) -> Result<(), APIError> {
866                 if channel_value_satoshis < 1000 {
867                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
868                 }
869
870                 let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
871                 let channel = Channel::new_outbound(&self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, config)?;
872                 let res = channel.get_open_channel(self.genesis_hash.clone());
873
874                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
875                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
876                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
877
878                 let mut channel_state = self.channel_state.lock().unwrap();
879                 match channel_state.by_id.entry(channel.channel_id()) {
880                         hash_map::Entry::Occupied(_) => {
881                                 if cfg!(feature = "fuzztarget") {
882                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
883                                 } else {
884                                         panic!("RNG is bad???");
885                                 }
886                         },
887                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
888                 }
889                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
890                         node_id: their_network_key,
891                         msg: res,
892                 });
893                 Ok(())
894         }
895
896         fn list_channels_with_filter<Fn: FnMut(&(&[u8; 32], &Channel<Signer>)) -> bool>(&self, f: Fn) -> Vec<ChannelDetails> {
897                 let mut res = Vec::new();
898                 {
899                         let channel_state = self.channel_state.lock().unwrap();
900                         res.reserve(channel_state.by_id.len());
901                         for (channel_id, channel) in channel_state.by_id.iter().filter(f) {
902                                 let (inbound_capacity_msat, outbound_capacity_msat) = channel.get_inbound_outbound_available_balance_msat();
903                                 res.push(ChannelDetails {
904                                         channel_id: (*channel_id).clone(),
905                                         short_channel_id: channel.get_short_channel_id(),
906                                         remote_network_id: channel.get_counterparty_node_id(),
907                                         counterparty_features: InitFeatures::empty(),
908                                         channel_value_satoshis: channel.get_value_satoshis(),
909                                         inbound_capacity_msat,
910                                         outbound_capacity_msat,
911                                         user_id: channel.get_user_id(),
912                                         is_live: channel.is_live(),
913                                         counterparty_forwarding_info: channel.counterparty_forwarding_info(),
914                                 });
915                         }
916                 }
917                 let per_peer_state = self.per_peer_state.read().unwrap();
918                 for chan in res.iter_mut() {
919                         if let Some(peer_state) = per_peer_state.get(&chan.remote_network_id) {
920                                 chan.counterparty_features = peer_state.lock().unwrap().latest_features.clone();
921                         }
922                 }
923                 res
924         }
925
926         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
927         /// more information.
928         pub fn list_channels(&self) -> Vec<ChannelDetails> {
929                 self.list_channels_with_filter(|_| true)
930         }
931
932         /// Gets the list of usable channels, in random order. Useful as an argument to
933         /// get_route to ensure non-announced channels are used.
934         ///
935         /// These are guaranteed to have their is_live value set to true, see the documentation for
936         /// ChannelDetails::is_live for more info on exactly what the criteria are.
937         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
938                 // Note we use is_live here instead of usable which leads to somewhat confused
939                 // internal/external nomenclature, but that's ok cause that's probably what the user
940                 // really wanted anyway.
941                 self.list_channels_with_filter(|&(_, ref channel)| channel.is_live())
942         }
943
944         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
945         /// will be accepted on the given channel, and after additional timeout/the closing of all
946         /// pending HTLCs, the channel will be closed on chain.
947         ///
948         /// May generate a SendShutdown message event on success, which should be relayed.
949         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
950                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
951
952                 let (mut failed_htlcs, chan_option) = {
953                         let mut channel_state_lock = self.channel_state.lock().unwrap();
954                         let channel_state = &mut *channel_state_lock;
955                         match channel_state.by_id.entry(channel_id.clone()) {
956                                 hash_map::Entry::Occupied(mut chan_entry) => {
957                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
958                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
959                                                 node_id: chan_entry.get().get_counterparty_node_id(),
960                                                 msg: shutdown_msg
961                                         });
962                                         if chan_entry.get().is_shutdown() {
963                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
964                                                         channel_state.short_to_id.remove(&short_id);
965                                                 }
966                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
967                                         } else { (failed_htlcs, None) }
968                                 },
969                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()})
970                         }
971                 };
972                 for htlc_source in failed_htlcs.drain(..) {
973                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
974                 }
975                 let chan_update = if let Some(chan) = chan_option {
976                         if let Ok(update) = self.get_channel_update(&chan) {
977                                 Some(update)
978                         } else { None }
979                 } else { None };
980
981                 if let Some(update) = chan_update {
982                         let mut channel_state = self.channel_state.lock().unwrap();
983                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
984                                 msg: update
985                         });
986                 }
987
988                 Ok(())
989         }
990
991         #[inline]
992         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
993                 let (monitor_update_option, mut failed_htlcs) = shutdown_res;
994                 log_trace!(self.logger, "Finishing force-closure of channel {} HTLCs to fail", failed_htlcs.len());
995                 for htlc_source in failed_htlcs.drain(..) {
996                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
997                 }
998                 if let Some((funding_txo, monitor_update)) = monitor_update_option {
999                         // There isn't anything we can do if we get an update failure - we're already
1000                         // force-closing. The monitor update on the required in-memory copy should broadcast
1001                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
1002                         // ignore the result here.
1003                         let _ = self.chain_monitor.update_channel(funding_txo, monitor_update);
1004                 }
1005         }
1006
1007         fn force_close_channel_with_peer(&self, channel_id: &[u8; 32], peer_node_id: Option<&PublicKey>) -> Result<(), APIError> {
1008                 let mut chan = {
1009                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1010                         let channel_state = &mut *channel_state_lock;
1011                         if let hash_map::Entry::Occupied(chan) = channel_state.by_id.entry(channel_id.clone()) {
1012                                 if let Some(node_id) = peer_node_id {
1013                                         if chan.get().get_counterparty_node_id() != *node_id {
1014                                                 // Error or Ok here doesn't matter - the result is only exposed publicly
1015                                                 // when peer_node_id is None anyway.
1016                                                 return Ok(());
1017                                         }
1018                                 }
1019                                 if let Some(short_id) = chan.get().get_short_channel_id() {
1020                                         channel_state.short_to_id.remove(&short_id);
1021                                 }
1022                                 chan.remove_entry().1
1023                         } else {
1024                                 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1025                         }
1026                 };
1027                 log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1028                 self.finish_force_close_channel(chan.force_shutdown(true));
1029                 if let Ok(update) = self.get_channel_update(&chan) {
1030                         let mut channel_state = self.channel_state.lock().unwrap();
1031                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1032                                 msg: update
1033                         });
1034                 }
1035
1036                 Ok(())
1037         }
1038
1039         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
1040         /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
1041         pub fn force_close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1042                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1043                 self.force_close_channel_with_peer(channel_id, None)
1044         }
1045
1046         /// Force close all channels, immediately broadcasting the latest local commitment transaction
1047         /// for each to the chain and rejecting new HTLCs on each.
1048         pub fn force_close_all_channels(&self) {
1049                 for chan in self.list_channels() {
1050                         let _ = self.force_close_channel(&chan.channel_id);
1051                 }
1052         }
1053
1054         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
1055                 macro_rules! return_malformed_err {
1056                         ($msg: expr, $err_code: expr) => {
1057                                 {
1058                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1059                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
1060                                                 channel_id: msg.channel_id,
1061                                                 htlc_id: msg.htlc_id,
1062                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
1063                                                 failure_code: $err_code,
1064                                         })), self.channel_state.lock().unwrap());
1065                                 }
1066                         }
1067                 }
1068
1069                 if let Err(_) = msg.onion_routing_packet.public_key {
1070                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
1071                 }
1072
1073                 let shared_secret = {
1074                         let mut arr = [0; 32];
1075                         arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1076                         arr
1077                 };
1078                 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
1079
1080                 if msg.onion_routing_packet.version != 0 {
1081                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1082                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1083                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
1084                         //receiving node would have to brute force to figure out which version was put in the
1085                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1086                         //node knows the HMAC matched, so they already know what is there...
1087                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1088                 }
1089
1090                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
1091                 hmac.input(&msg.onion_routing_packet.hop_data);
1092                 hmac.input(&msg.payment_hash.0[..]);
1093                 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
1094                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
1095                 }
1096
1097                 let mut channel_state = None;
1098                 macro_rules! return_err {
1099                         ($msg: expr, $err_code: expr, $data: expr) => {
1100                                 {
1101                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1102                                         if channel_state.is_none() {
1103                                                 channel_state = Some(self.channel_state.lock().unwrap());
1104                                         }
1105                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1106                                                 channel_id: msg.channel_id,
1107                                                 htlc_id: msg.htlc_id,
1108                                                 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1109                                         })), channel_state.unwrap());
1110                                 }
1111                         }
1112                 }
1113
1114                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1115                 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
1116                 let (next_hop_data, next_hop_hmac) = {
1117                         match msgs::OnionHopData::read(&mut chacha_stream) {
1118                                 Err(err) => {
1119                                         let error_code = match err {
1120                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1121                                                 msgs::DecodeError::UnknownRequiredFeature|
1122                                                 msgs::DecodeError::InvalidValue|
1123                                                 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
1124                                                 _ => 0x2000 | 2, // Should never happen
1125                                         };
1126                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1127                                 },
1128                                 Ok(msg) => {
1129                                         let mut hmac = [0; 32];
1130                                         if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
1131                                                 return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
1132                                         }
1133                                         (msg, hmac)
1134                                 },
1135                         }
1136                 };
1137
1138                 let pending_forward_info = if next_hop_hmac == [0; 32] {
1139                                 #[cfg(test)]
1140                                 {
1141                                         // In tests, make sure that the initial onion pcket data is, at least, non-0.
1142                                         // We could do some fancy randomness test here, but, ehh, whatever.
1143                                         // This checks for the issue where you can calculate the path length given the
1144                                         // onion data as all the path entries that the originator sent will be here
1145                                         // as-is (and were originally 0s).
1146                                         // Of course reverse path calculation is still pretty easy given naive routing
1147                                         // algorithms, but this fixes the most-obvious case.
1148                                         let mut next_bytes = [0; 32];
1149                                         chacha_stream.read_exact(&mut next_bytes).unwrap();
1150                                         assert_ne!(next_bytes[..], [0; 32][..]);
1151                                         chacha_stream.read_exact(&mut next_bytes).unwrap();
1152                                         assert_ne!(next_bytes[..], [0; 32][..]);
1153                                 }
1154
1155                                 // OUR PAYMENT!
1156                                 // final_expiry_too_soon
1157                                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure we have at least
1158                                 // HTLC_FAIL_BACK_BUFFER blocks to go.
1159                                 // Also, ensure that, in the case of an unknown payment hash, our payment logic has enough time to fail the HTLC backward
1160                                 // before our onchain logic triggers a channel closure (see HTLC_FAIL_BACK_BUFFER rational).
1161                                 if (msg.cltv_expiry as u64) <= self.latest_block_height.load(Ordering::Acquire) as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1162                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1163                                 }
1164                                 // final_incorrect_htlc_amount
1165                                 if next_hop_data.amt_to_forward > msg.amount_msat {
1166                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1167                                 }
1168                                 // final_incorrect_cltv_expiry
1169                                 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
1170                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1171                                 }
1172
1173                                 let payment_data = match next_hop_data.format {
1174                                         msgs::OnionHopDataFormat::Legacy { .. } => None,
1175                                         msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1176                                         msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1177                                 };
1178
1179                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1180                                 // message, however that would leak that we are the recipient of this payment, so
1181                                 // instead we stay symmetric with the forwarding case, only responding (after a
1182                                 // delay) once they've send us a commitment_signed!
1183
1184                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
1185                                         routing: PendingHTLCRouting::Receive {
1186                                                 payment_data,
1187                                                 incoming_cltv_expiry: msg.cltv_expiry,
1188                                         },
1189                                         payment_hash: msg.payment_hash.clone(),
1190                                         incoming_shared_secret: shared_secret,
1191                                         amt_to_forward: next_hop_data.amt_to_forward,
1192                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1193                                 })
1194                         } else {
1195                                 let mut new_packet_data = [0; 20*65];
1196                                 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1197                                 #[cfg(debug_assertions)]
1198                                 {
1199                                         // Check two things:
1200                                         // a) that the behavior of our stream here will return Ok(0) even if the TLV
1201                                         //    read above emptied out our buffer and the unwrap() wont needlessly panic
1202                                         // b) that we didn't somehow magically end up with extra data.
1203                                         let mut t = [0; 1];
1204                                         debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1205                                 }
1206                                 // Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
1207                                 // fill the onion hop data we'll forward to our next-hop peer.
1208                                 chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
1209
1210                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1211
1212                                 let blinding_factor = {
1213                                         let mut sha = Sha256::engine();
1214                                         sha.input(&new_pubkey.serialize()[..]);
1215                                         sha.input(&shared_secret);
1216                                         Sha256::from_engine(sha).into_inner()
1217                                 };
1218
1219                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1220                                         Err(e)
1221                                 } else { Ok(new_pubkey) };
1222
1223                                 let outgoing_packet = msgs::OnionPacket {
1224                                         version: 0,
1225                                         public_key,
1226                                         hop_data: new_packet_data,
1227                                         hmac: next_hop_hmac.clone(),
1228                                 };
1229
1230                                 let short_channel_id = match next_hop_data.format {
1231                                         msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1232                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1233                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
1234                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1235                                         },
1236                                 };
1237
1238                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
1239                                         routing: PendingHTLCRouting::Forward {
1240                                                 onion_packet: outgoing_packet,
1241                                                 short_channel_id,
1242                                         },
1243                                         payment_hash: msg.payment_hash.clone(),
1244                                         incoming_shared_secret: shared_secret,
1245                                         amt_to_forward: next_hop_data.amt_to_forward,
1246                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1247                                 })
1248                         };
1249
1250                 channel_state = Some(self.channel_state.lock().unwrap());
1251                 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1252                         // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
1253                         // with a short_channel_id of 0. This is important as various things later assume
1254                         // short_channel_id is non-0 in any ::Forward.
1255                         if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
1256                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1257                                 let forwarding_id = match id_option {
1258                                         None => { // unknown_next_peer
1259                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1260                                         },
1261                                         Some(id) => id.clone(),
1262                                 };
1263                                 if let Some((err, code, chan_update)) = loop {
1264                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1265
1266                                         // Note that we could technically not return an error yet here and just hope
1267                                         // that the connection is reestablished or monitor updated by the time we get
1268                                         // around to doing the actual forward, but better to fail early if we can and
1269                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1270                                         // on a small/per-node/per-channel scale.
1271                                         if !chan.is_live() { // channel_disabled
1272                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1273                                         }
1274                                         if *amt_to_forward < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
1275                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1276                                         }
1277                                         let fee = amt_to_forward.checked_mul(chan.get_fee_proportional_millionths() as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_holder_fee_base_msat(&self.fee_estimator) as u64) });
1278                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1279                                                 break Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, Some(self.get_channel_update(chan).unwrap())));
1280                                         }
1281                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + chan.get_cltv_expiry_delta() as u64 { // incorrect_cltv_expiry
1282                                                 break Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, Some(self.get_channel_update(chan).unwrap())));
1283                                         }
1284                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1285                                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now, but we want to be robust wrt to counterparty
1286                                         // packet sanitization (see HTLC_FAIL_BACK_BUFFER rational)
1287                                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
1288                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1289                                         }
1290                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1291                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1292                                         }
1293                                         // In theory, we would be safe against unitentional channel-closure, if we only required a margin of LATENCY_GRACE_PERIOD_BLOCKS.
1294                                         // But, to be safe against policy reception, we use a longuer delay.
1295                                         if (*outgoing_cltv_value) as u64 <= (cur_height + HTLC_FAIL_BACK_BUFFER) as u64 {
1296                                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1297                                         }
1298
1299                                         break None;
1300                                 }
1301                                 {
1302                                         let mut res = Vec::with_capacity(8 + 128);
1303                                         if let Some(chan_update) = chan_update {
1304                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1305                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1306                                                 }
1307                                                 else if code == 0x1000 | 13 {
1308                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1309                                                 }
1310                                                 else if code == 0x1000 | 20 {
1311                                                         // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
1312                                                         res.extend_from_slice(&byte_utils::be16_to_array(0));
1313                                                 }
1314                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1315                                         }
1316                                         return_err!(err, code, &res[..]);
1317                                 }
1318                         }
1319                 }
1320
1321                 (pending_forward_info, channel_state.unwrap())
1322         }
1323
1324         /// only fails if the channel does not yet have an assigned short_id
1325         /// May be called with channel_state already locked!
1326         fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
1327                 let short_channel_id = match chan.get_short_channel_id() {
1328                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
1329                         Some(id) => id,
1330                 };
1331
1332                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
1333
1334                 let unsigned = msgs::UnsignedChannelUpdate {
1335                         chain_hash: self.genesis_hash,
1336                         short_channel_id,
1337                         timestamp: chan.get_update_time_counter(),
1338                         flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
1339                         cltv_expiry_delta: chan.get_cltv_expiry_delta(),
1340                         htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
1341                         htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()),
1342                         fee_base_msat: chan.get_holder_fee_base_msat(&self.fee_estimator),
1343                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1344                         excess_data: Vec::new(),
1345                 };
1346
1347                 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1348                 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1349
1350                 Ok(msgs::ChannelUpdate {
1351                         signature: sig,
1352                         contents: unsigned
1353                 })
1354         }
1355
1356         // Only public for testing, this should otherwise never be called direcly
1357         pub(crate) fn send_payment_along_path(&self, path: &Vec<RouteHop>, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>, total_value: u64, cur_height: u32) -> Result<(), APIError> {
1358                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
1359                 let prng_seed = self.keys_manager.get_secure_random_bytes();
1360                 let session_priv = SecretKey::from_slice(&self.keys_manager.get_secure_random_bytes()[..]).expect("RNG is busted");
1361
1362                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
1363                         .map_err(|_| APIError::RouteError{err: "Pubkey along hop was maliciously selected"})?;
1364                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height)?;
1365                 if onion_utils::route_size_insane(&onion_payloads) {
1366                         return Err(APIError::RouteError{err: "Route size too large considering onion data"});
1367                 }
1368                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
1369
1370                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1371
1372                 let err: Result<(), _> = loop {
1373                         let mut channel_lock = self.channel_state.lock().unwrap();
1374                         let id = match channel_lock.short_to_id.get(&path.first().unwrap().short_channel_id) {
1375                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
1376                                 Some(id) => id.clone(),
1377                         };
1378
1379                         let channel_state = &mut *channel_lock;
1380                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1381                                 match {
1382                                         if chan.get().get_counterparty_node_id() != path.first().unwrap().pubkey {
1383                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1384                                         }
1385                                         if !chan.get().is_live() {
1386                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
1387                                         }
1388                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1389                                                 path: path.clone(),
1390                                                 session_priv: session_priv.clone(),
1391                                                 first_hop_htlc_msat: htlc_msat,
1392                                         }, onion_packet, &self.logger), channel_state, chan)
1393                                 } {
1394                                         Some((update_add, commitment_signed, monitor_update)) => {
1395                                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1396                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1397                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1398                                                         // that we will resend the commitment update once monitor updating
1399                                                         // is restored. Therefore, we must return an error indicating that
1400                                                         // it is unsafe to retry the payment wholesale, which we do in the
1401                                                         // send_payment check for MonitorUpdateFailed, below.
1402                                                         return Err(APIError::MonitorUpdateFailed);
1403                                                 }
1404
1405                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1406                                                         node_id: path.first().unwrap().pubkey,
1407                                                         updates: msgs::CommitmentUpdate {
1408                                                                 update_add_htlcs: vec![update_add],
1409                                                                 update_fulfill_htlcs: Vec::new(),
1410                                                                 update_fail_htlcs: Vec::new(),
1411                                                                 update_fail_malformed_htlcs: Vec::new(),
1412                                                                 update_fee: None,
1413                                                                 commitment_signed,
1414                                                         },
1415                                                 });
1416                                         },
1417                                         None => {},
1418                                 }
1419                         } else { unreachable!(); }
1420                         return Ok(());
1421                 };
1422
1423                 match handle_error!(self, err, path.first().unwrap().pubkey) {
1424                         Ok(_) => unreachable!(),
1425                         Err(e) => {
1426                                 Err(APIError::ChannelUnavailable { err: e.err })
1427                         },
1428                 }
1429         }
1430
1431         /// Sends a payment along a given route.
1432         ///
1433         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1434         /// fields for more info.
1435         ///
1436         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1437         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1438         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1439         /// specified in the last hop in the route! Thus, you should probably do your own
1440         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1441         /// payment") and prevent double-sends yourself.
1442         ///
1443         /// May generate SendHTLCs message(s) event on success, which should be relayed.
1444         ///
1445         /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1446         /// each entry matching the corresponding-index entry in the route paths, see
1447         /// PaymentSendFailure for more info.
1448         ///
1449         /// In general, a path may raise:
1450         ///  * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1451         ///    node public key) is specified.
1452         ///  * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1453         ///    (including due to previous monitor update failure or new permanent monitor update
1454         ///    failure).
1455         ///  * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1456         ///    relevant updates.
1457         ///
1458         /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1459         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1460         /// different route unless you intend to pay twice!
1461         ///
1462         /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1463         /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1464         /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1465         /// must not contain multiple paths as multi-path payments require a recipient-provided
1466         /// payment_secret.
1467         /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
1468         /// bit set (either as required or as available). If multiple paths are present in the Route,
1469         /// we assume the invoice had the basic_mpp feature set.
1470         pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>) -> Result<(), PaymentSendFailure> {
1471                 if route.paths.len() < 1 {
1472                         return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "There must be at least one path to send over"}));
1473                 }
1474                 if route.paths.len() > 10 {
1475                         // This limit is completely arbitrary - there aren't any real fundamental path-count
1476                         // limits. After we support retrying individual paths we should likely bump this, but
1477                         // for now more than 10 paths likely carries too much one-path failure.
1478                         return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "Sending over more than 10 paths is not currently supported"}));
1479                 }
1480                 let mut total_value = 0;
1481                 let our_node_id = self.get_our_node_id();
1482                 let mut path_errs = Vec::with_capacity(route.paths.len());
1483                 'path_check: for path in route.paths.iter() {
1484                         if path.len() < 1 || path.len() > 20 {
1485                                 path_errs.push(Err(APIError::RouteError{err: "Path didn't go anywhere/had bogus size"}));
1486                                 continue 'path_check;
1487                         }
1488                         for (idx, hop) in path.iter().enumerate() {
1489                                 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1490                                         path_errs.push(Err(APIError::RouteError{err: "Path went through us but wasn't a simple rebalance loop to us"}));
1491                                         continue 'path_check;
1492                                 }
1493                         }
1494                         total_value += path.last().unwrap().fee_msat;
1495                         path_errs.push(Ok(()));
1496                 }
1497                 if path_errs.iter().any(|e| e.is_err()) {
1498                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1499                 }
1500
1501                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1502                 let mut results = Vec::new();
1503                 for path in route.paths.iter() {
1504                         results.push(self.send_payment_along_path(&path, &payment_hash, payment_secret, total_value, cur_height));
1505                 }
1506                 let mut has_ok = false;
1507                 let mut has_err = false;
1508                 for res in results.iter() {
1509                         if res.is_ok() { has_ok = true; }
1510                         if res.is_err() { has_err = true; }
1511                         if let &Err(APIError::MonitorUpdateFailed) = res {
1512                                 // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1513                                 // PartialFailure.
1514                                 has_err = true;
1515                                 has_ok = true;
1516                                 break;
1517                         }
1518                 }
1519                 if has_err && has_ok {
1520                         Err(PaymentSendFailure::PartialFailure(results))
1521                 } else if has_err {
1522                         Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1523                 } else {
1524                         Ok(())
1525                 }
1526         }
1527
1528         /// Call this upon creation of a funding transaction for the given channel.
1529         ///
1530         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1531         /// or your counterparty can steal your funds!
1532         ///
1533         /// Panics if a funding transaction has already been provided for this channel.
1534         ///
1535         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1536         /// be trivially prevented by using unique funding transaction keys per-channel).
1537         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1538                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1539
1540                 let (chan, msg) = {
1541                         let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
1542                                 Some(mut chan) => {
1543                                         (chan.get_outbound_funding_created(funding_txo, &self.logger)
1544                                                 .map_err(|e| if let ChannelError::Close(msg) = e {
1545                                                         MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
1546                                                 } else { unreachable!(); })
1547                                         , chan)
1548                                 },
1549                                 None => return
1550                         };
1551                         match handle_error!(self, res, chan.get_counterparty_node_id()) {
1552                                 Ok(funding_msg) => {
1553                                         (chan, funding_msg)
1554                                 },
1555                                 Err(_) => { return; }
1556                         }
1557                 };
1558
1559                 let mut channel_state = self.channel_state.lock().unwrap();
1560                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1561                         node_id: chan.get_counterparty_node_id(),
1562                         msg,
1563                 });
1564                 match channel_state.by_id.entry(chan.channel_id()) {
1565                         hash_map::Entry::Occupied(_) => {
1566                                 panic!("Generated duplicate funding txid?");
1567                         },
1568                         hash_map::Entry::Vacant(e) => {
1569                                 e.insert(chan);
1570                         }
1571                 }
1572         }
1573
1574         fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
1575                 if !chan.should_announce() {
1576                         log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
1577                         return None
1578                 }
1579
1580                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1581                         Ok(res) => res,
1582                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1583                 };
1584                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1585                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1586
1587                 Some(msgs::AnnouncementSignatures {
1588                         channel_id: chan.channel_id(),
1589                         short_channel_id: chan.get_short_channel_id().unwrap(),
1590                         node_signature: our_node_sig,
1591                         bitcoin_signature: our_bitcoin_sig,
1592                 })
1593         }
1594
1595         #[allow(dead_code)]
1596         // Messages of up to 64KB should never end up more than half full with addresses, as that would
1597         // be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1598         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1599         // message...
1600         const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1601         #[deny(const_err)]
1602         #[allow(dead_code)]
1603         // ...by failing to compile if the number of addresses that would be half of a message is
1604         // smaller than 500:
1605         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1606
1607         /// Generates a signed node_announcement from the given arguments and creates a
1608         /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1609         /// seen a channel_announcement from us (ie unless we have public channels open).
1610         ///
1611         /// RGB is a node "color" and alias is a printable human-readable string to describe this node
1612         /// to humans. They carry no in-protocol meaning.
1613         ///
1614         /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1615         /// incoming connections. These will be broadcast to the network, publicly tying these
1616         /// addresses together. If you wish to preserve user privacy, addresses should likely contain
1617         /// only Tor Onion addresses.
1618         ///
1619         /// Panics if addresses is absurdly large (more than 500).
1620         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<NetAddress>) {
1621                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1622
1623                 if addresses.len() > 500 {
1624                         panic!("More than half the message size was taken up by public addresses!");
1625                 }
1626
1627                 let announcement = msgs::UnsignedNodeAnnouncement {
1628                         features: NodeFeatures::known(),
1629                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1630                         node_id: self.get_our_node_id(),
1631                         rgb, alias, addresses,
1632                         excess_address_data: Vec::new(),
1633                         excess_data: Vec::new(),
1634                 };
1635                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1636
1637                 let mut channel_state = self.channel_state.lock().unwrap();
1638                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1639                         msg: msgs::NodeAnnouncement {
1640                                 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1641                                 contents: announcement
1642                         },
1643                 });
1644         }
1645
1646         /// Processes HTLCs which are pending waiting on random forward delay.
1647         ///
1648         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1649         /// Will likely generate further events.
1650         pub fn process_pending_htlc_forwards(&self) {
1651                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1652
1653                 let mut new_events = Vec::new();
1654                 let mut failed_forwards = Vec::new();
1655                 let mut handle_errors = Vec::new();
1656                 {
1657                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1658                         let channel_state = &mut *channel_state_lock;
1659
1660                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1661                                 if short_chan_id != 0 {
1662                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1663                                                 Some(chan_id) => chan_id.clone(),
1664                                                 None => {
1665                                                         failed_forwards.reserve(pending_forwards.len());
1666                                                         for forward_info in pending_forwards.drain(..) {
1667                                                                 match forward_info {
1668                                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info,
1669                                                                                                    prev_funding_outpoint } => {
1670                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1671                                                                                         short_channel_id: prev_short_channel_id,
1672                                                                                         outpoint: prev_funding_outpoint,
1673                                                                                         htlc_id: prev_htlc_id,
1674                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1675                                                                                 });
1676                                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash,
1677                                                                                         HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() }
1678                                                                                 ));
1679                                                                         },
1680                                                                         HTLCForwardInfo::FailHTLC { .. } => {
1681                                                                                 // Channel went away before we could fail it. This implies
1682                                                                                 // the channel is now on chain and our counterparty is
1683                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
1684                                                                                 // problem, not ours.
1685                                                                         }
1686                                                                 }
1687                                                         }
1688                                                         continue;
1689                                                 }
1690                                         };
1691                                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1692                                                 let mut add_htlc_msgs = Vec::new();
1693                                                 let mut fail_htlc_msgs = Vec::new();
1694                                                 for forward_info in pending_forwards.drain(..) {
1695                                                         match forward_info {
1696                                                                 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1697                                                                                 routing: PendingHTLCRouting::Forward {
1698                                                                                         onion_packet, ..
1699                                                                                 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
1700                                                                                 prev_funding_outpoint } => {
1701                                                                         log_trace!(self.logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", log_bytes!(payment_hash.0), prev_short_channel_id, short_chan_id);
1702                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1703                                                                                 short_channel_id: prev_short_channel_id,
1704                                                                                 outpoint: prev_funding_outpoint,
1705                                                                                 htlc_id: prev_htlc_id,
1706                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
1707                                                                         });
1708                                                                         match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1709                                                                                 Err(e) => {
1710                                                                                         if let ChannelError::Ignore(msg) = e {
1711                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1712                                                                                         } else {
1713                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
1714                                                                                         }
1715                                                                                         let chan_update = self.get_channel_update(chan.get()).unwrap();
1716                                                                                         failed_forwards.push((htlc_source, payment_hash,
1717                                                                                                 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1718                                                                                         ));
1719                                                                                         continue;
1720                                                                                 },
1721                                                                                 Ok(update_add) => {
1722                                                                                         match update_add {
1723                                                                                                 Some(msg) => { add_htlc_msgs.push(msg); },
1724                                                                                                 None => {
1725                                                                                                         // Nothing to do here...we're waiting on a remote
1726                                                                                                         // revoke_and_ack before we can add anymore HTLCs. The Channel
1727                                                                                                         // will automatically handle building the update_add_htlc and
1728                                                                                                         // commitment_signed messages when we can.
1729                                                                                                         // TODO: Do some kind of timer to set the channel as !is_live()
1730                                                                                                         // as we don't really want others relying on us relaying through
1731                                                                                                         // this channel currently :/.
1732                                                                                                 }
1733                                                                                         }
1734                                                                                 }
1735                                                                         }
1736                                                                 },
1737                                                                 HTLCForwardInfo::AddHTLC { .. } => {
1738                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1739                                                                 },
1740                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1741                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1742                                                                         match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1743                                                                                 Err(e) => {
1744                                                                                         if let ChannelError::Ignore(msg) = e {
1745                                                                                                 log_trace!(self.logger, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1746                                                                                         } else {
1747                                                                                                 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1748                                                                                         }
1749                                                                                         // fail-backs are best-effort, we probably already have one
1750                                                                                         // pending, and if not that's OK, if not, the channel is on
1751                                                                                         // the chain and sending the HTLC-Timeout is their problem.
1752                                                                                         continue;
1753                                                                                 },
1754                                                                                 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1755                                                                                 Ok(None) => {
1756                                                                                         // Nothing to do here...we're waiting on a remote
1757                                                                                         // revoke_and_ack before we can update the commitment
1758                                                                                         // transaction. The Channel will automatically handle
1759                                                                                         // building the update_fail_htlc and commitment_signed
1760                                                                                         // messages when we can.
1761                                                                                         // We don't need any kind of timer here as they should fail
1762                                                                                         // the channel onto the chain if they can't get our
1763                                                                                         // update_fail_htlc in time, it's not our problem.
1764                                                                                 }
1765                                                                         }
1766                                                                 },
1767                                                         }
1768                                                 }
1769
1770                                                 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1771                                                         let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
1772                                                                 Ok(res) => res,
1773                                                                 Err(e) => {
1774                                                                         // We surely failed send_commitment due to bad keys, in that case
1775                                                                         // close channel and then send error message to peer.
1776                                                                         let counterparty_node_id = chan.get().get_counterparty_node_id();
1777                                                                         let err: Result<(), _>  = match e {
1778                                                                                 ChannelError::Ignore(_) => {
1779                                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1780                                                                                 },
1781                                                                                 ChannelError::Close(msg) => {
1782                                                                                         log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1783                                                                                         let (channel_id, mut channel) = chan.remove_entry();
1784                                                                                         if let Some(short_id) = channel.get_short_channel_id() {
1785                                                                                                 channel_state.short_to_id.remove(&short_id);
1786                                                                                         }
1787                                                                                         Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update(&channel).ok()))
1788                                                                                 },
1789                                                                                 ChannelError::CloseDelayBroadcast(_) => { panic!("Wait is only generated on receipt of channel_reestablish, which is handled by try_chan_entry, we don't bother to support it here"); }
1790                                                                         };
1791                                                                         handle_errors.push((counterparty_node_id, err));
1792                                                                         continue;
1793                                                                 }
1794                                                         };
1795                                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1796                                                                 handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1797                                                                 continue;
1798                                                         }
1799                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1800                                                                 node_id: chan.get().get_counterparty_node_id(),
1801                                                                 updates: msgs::CommitmentUpdate {
1802                                                                         update_add_htlcs: add_htlc_msgs,
1803                                                                         update_fulfill_htlcs: Vec::new(),
1804                                                                         update_fail_htlcs: fail_htlc_msgs,
1805                                                                         update_fail_malformed_htlcs: Vec::new(),
1806                                                                         update_fee: None,
1807                                                                         commitment_signed: commitment_msg,
1808                                                                 },
1809                                                         });
1810                                                 }
1811                                         } else {
1812                                                 unreachable!();
1813                                         }
1814                                 } else {
1815                                         for forward_info in pending_forwards.drain(..) {
1816                                                 match forward_info {
1817                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1818                                                                         routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
1819                                                                         incoming_shared_secret, payment_hash, amt_to_forward, .. },
1820                                                                         prev_funding_outpoint } => {
1821                                                                 let prev_hop = HTLCPreviousHopData {
1822                                                                         short_channel_id: prev_short_channel_id,
1823                                                                         outpoint: prev_funding_outpoint,
1824                                                                         htlc_id: prev_htlc_id,
1825                                                                         incoming_packet_shared_secret: incoming_shared_secret,
1826                                                                 };
1827
1828                                                                 let mut total_value = 0;
1829                                                                 let payment_secret_opt =
1830                                                                         if let &Some(ref data) = &payment_data { Some(data.payment_secret.clone()) } else { None };
1831                                                                 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, payment_secret_opt))
1832                                                                         .or_insert(Vec::new());
1833                                                                 htlcs.push(ClaimableHTLC {
1834                                                                         prev_hop,
1835                                                                         value: amt_to_forward,
1836                                                                         payment_data: payment_data.clone(),
1837                                                                         cltv_expiry: incoming_cltv_expiry,
1838                                                                 });
1839                                                                 if let &Some(ref data) = &payment_data {
1840                                                                         for htlc in htlcs.iter() {
1841                                                                                 total_value += htlc.value;
1842                                                                                 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1843                                                                                         total_value = msgs::MAX_VALUE_MSAT;
1844                                                                                 }
1845                                                                                 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1846                                                                         }
1847                                                                         if total_value >= msgs::MAX_VALUE_MSAT || total_value > data.total_msat  {
1848                                                                                 for htlc in htlcs.iter() {
1849                                                                                         let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1850                                                                                         htlc_msat_height_data.extend_from_slice(
1851                                                                                                 &byte_utils::be32_to_array(
1852                                                                                                         self.latest_block_height.load(Ordering::Acquire)
1853                                                                                                                 as u32,
1854                                                                                                 ),
1855                                                                                         );
1856                                                                                         failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1857                                                                                                         short_channel_id: htlc.prev_hop.short_channel_id,
1858                                                                                                         outpoint: prev_funding_outpoint,
1859                                                                                                         htlc_id: htlc.prev_hop.htlc_id,
1860                                                                                                         incoming_packet_shared_secret: htlc.prev_hop.incoming_packet_shared_secret,
1861                                                                                                 }), payment_hash,
1862                                                                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data }
1863                                                                                         ));
1864                                                                                 }
1865                                                                         } else if total_value == data.total_msat {
1866                                                                                 new_events.push(events::Event::PaymentReceived {
1867                                                                                         payment_hash,
1868                                                                                         payment_secret: Some(data.payment_secret),
1869                                                                                         amt: total_value,
1870                                                                                 });
1871                                                                         }
1872                                                                 } else {
1873                                                                         new_events.push(events::Event::PaymentReceived {
1874                                                                                 payment_hash,
1875                                                                                 payment_secret: None,
1876                                                                                 amt: amt_to_forward,
1877                                                                         });
1878                                                                 }
1879                                                         },
1880                                                         HTLCForwardInfo::AddHTLC { .. } => {
1881                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1882                                                         },
1883                                                         HTLCForwardInfo::FailHTLC { .. } => {
1884                                                                 panic!("Got pending fail of our own HTLC");
1885                                                         }
1886                                                 }
1887                                         }
1888                                 }
1889                         }
1890                 }
1891
1892                 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1893                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1894                 }
1895
1896                 for (counterparty_node_id, err) in handle_errors.drain(..) {
1897                         let _ = handle_error!(self, err, counterparty_node_id);
1898                 }
1899
1900                 if new_events.is_empty() { return }
1901                 let mut events = self.pending_events.lock().unwrap();
1902                 events.append(&mut new_events);
1903         }
1904
1905         /// Free the background events, generally called from timer_chan_freshness_every_min.
1906         ///
1907         /// Exposed for testing to allow us to process events quickly without generating accidental
1908         /// BroadcastChannelUpdate events in timer_chan_freshness_every_min.
1909         ///
1910         /// Expects the caller to have a total_consistency_lock read lock.
1911         fn process_background_events(&self) {
1912                 let mut background_events = Vec::new();
1913                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
1914                 for event in background_events.drain(..) {
1915                         match event {
1916                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
1917                                         // The channel has already been closed, so no use bothering to care about the
1918                                         // monitor updating completing.
1919                                         let _ = self.chain_monitor.update_channel(funding_txo, update);
1920                                 },
1921                         }
1922                 }
1923         }
1924
1925         #[cfg(any(test, feature = "_test_utils"))]
1926         pub(crate) fn test_process_background_events(&self) {
1927                 self.process_background_events();
1928         }
1929
1930         /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1931         /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1932         /// to inform the network about the uselessness of these channels.
1933         ///
1934         /// This method handles all the details, and must be called roughly once per minute.
1935         ///
1936         /// Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
1937         pub fn timer_chan_freshness_every_min(&self) {
1938                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1939                 self.process_background_events();
1940
1941                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1942                 let channel_state = &mut *channel_state_lock;
1943                 for (_, chan) in channel_state.by_id.iter_mut() {
1944                         if chan.is_disabled_staged() && !chan.is_live() {
1945                                 if let Ok(update) = self.get_channel_update(&chan) {
1946                                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1947                                                 msg: update
1948                                         });
1949                                 }
1950                                 chan.to_fresh();
1951                         } else if chan.is_disabled_staged() && chan.is_live() {
1952                                 chan.to_fresh();
1953                         } else if chan.is_disabled_marked() {
1954                                 chan.to_disabled_staged();
1955                         }
1956                 }
1957         }
1958
1959         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1960         /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1961         /// along the path (including in our own channel on which we received it).
1962         /// Returns false if no payment was found to fail backwards, true if the process of failing the
1963         /// HTLC backwards has been started.
1964         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>) -> bool {
1965                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1966
1967                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1968                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1969                 if let Some(mut sources) = removed_source {
1970                         for htlc in sources.drain(..) {
1971                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1972                                 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1973                                 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
1974                                         self.latest_block_height.load(Ordering::Acquire) as u32,
1975                                 ));
1976                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1977                                                 HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
1978                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data });
1979                         }
1980                         true
1981                 } else { false }
1982         }
1983
1984         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
1985         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
1986         // be surfaced to the user.
1987         fn fail_holding_cell_htlcs(&self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32]) {
1988                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
1989                         match htlc_src {
1990                                 HTLCSource::PreviousHopData(HTLCPreviousHopData { .. }) => {
1991                                         let (failure_code, onion_failure_data) =
1992                                                 match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
1993                                                         hash_map::Entry::Occupied(chan_entry) => {
1994                                                                 if let Ok(upd) = self.get_channel_update(&chan_entry.get()) {
1995                                                                         (0x1000|7, upd.encode_with_len())
1996                                                                 } else {
1997                                                                         (0x4000|10, Vec::new())
1998                                                                 }
1999                                                         },
2000                                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
2001                                                 };
2002                                         let channel_state = self.channel_state.lock().unwrap();
2003                                         self.fail_htlc_backwards_internal(channel_state,
2004                                                 htlc_src, &payment_hash, HTLCFailReason::Reason { failure_code, data: onion_failure_data});
2005                                 },
2006                                 HTLCSource::OutboundRoute { .. } => {
2007                                         self.pending_events.lock().unwrap().push(
2008                                                 events::Event::PaymentFailed {
2009                                                         payment_hash,
2010                                                         rejected_by_dest: false,
2011 #[cfg(test)]
2012                                                         error_code: None,
2013 #[cfg(test)]
2014                                                         error_data: None,
2015                                                 }
2016                                         )
2017                                 },
2018                         };
2019                 }
2020         }
2021
2022         /// Fails an HTLC backwards to the sender of it to us.
2023         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
2024         /// There are several callsites that do stupid things like loop over a list of payment_hashes
2025         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
2026         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
2027         /// still-available channels.
2028         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
2029                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
2030                 //identify whether we sent it or not based on the (I presume) very different runtime
2031                 //between the branches here. We should make this async and move it into the forward HTLCs
2032                 //timer handling.
2033
2034                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
2035                 // from block_connected which may run during initialization prior to the chain_monitor
2036                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
2037                 match source {
2038                         HTLCSource::OutboundRoute { ref path, .. } => {
2039                                 log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2040                                 mem::drop(channel_state_lock);
2041                                 match &onion_error {
2042                                         &HTLCFailReason::LightningError { ref err } => {
2043 #[cfg(test)]
2044                                                 let (channel_update, payment_retryable, onion_error_code, onion_error_data) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2045 #[cfg(not(test))]
2046                                                 let (channel_update, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2047                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
2048                                                 // process_onion_failure we should close that channel as it implies our
2049                                                 // next-hop is needlessly blaming us!
2050                                                 if let Some(update) = channel_update {
2051                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
2052                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
2053                                                                         update,
2054                                                                 }
2055                                                         );
2056                                                 }
2057                                                 self.pending_events.lock().unwrap().push(
2058                                                         events::Event::PaymentFailed {
2059                                                                 payment_hash: payment_hash.clone(),
2060                                                                 rejected_by_dest: !payment_retryable,
2061 #[cfg(test)]
2062                                                                 error_code: onion_error_code,
2063 #[cfg(test)]
2064                                                                 error_data: onion_error_data
2065                                                         }
2066                                                 );
2067                                         },
2068                                         &HTLCFailReason::Reason {
2069 #[cfg(test)]
2070                                                         ref failure_code,
2071 #[cfg(test)]
2072                                                         ref data,
2073                                                         .. } => {
2074                                                 // we get a fail_malformed_htlc from the first hop
2075                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
2076                                                 // failures here, but that would be insufficient as get_route
2077                                                 // generally ignores its view of our own channels as we provide them via
2078                                                 // ChannelDetails.
2079                                                 // TODO: For non-temporary failures, we really should be closing the
2080                                                 // channel here as we apparently can't relay through them anyway.
2081                                                 self.pending_events.lock().unwrap().push(
2082                                                         events::Event::PaymentFailed {
2083                                                                 payment_hash: payment_hash.clone(),
2084                                                                 rejected_by_dest: path.len() == 1,
2085 #[cfg(test)]
2086                                                                 error_code: Some(*failure_code),
2087 #[cfg(test)]
2088                                                                 error_data: Some(data.clone()),
2089                                                         }
2090                                                 );
2091                                         }
2092                                 }
2093                         },
2094                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
2095                                 let err_packet = match onion_error {
2096                                         HTLCFailReason::Reason { failure_code, data } => {
2097                                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
2098                                                 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
2099                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
2100                                         },
2101                                         HTLCFailReason::LightningError { err } => {
2102                                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
2103                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
2104                                         }
2105                                 };
2106
2107                                 let mut forward_event = None;
2108                                 if channel_state_lock.forward_htlcs.is_empty() {
2109                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
2110                                 }
2111                                 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
2112                                         hash_map::Entry::Occupied(mut entry) => {
2113                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
2114                                         },
2115                                         hash_map::Entry::Vacant(entry) => {
2116                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
2117                                         }
2118                                 }
2119                                 mem::drop(channel_state_lock);
2120                                 if let Some(time) = forward_event {
2121                                         let mut pending_events = self.pending_events.lock().unwrap();
2122                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2123                                                 time_forwardable: time
2124                                         });
2125                                 }
2126                         },
2127                 }
2128         }
2129
2130         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
2131         /// generating message events for the net layer to claim the payment, if possible. Thus, you
2132         /// should probably kick the net layer to go send messages if this returns true!
2133         ///
2134         /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
2135         /// available within a few percent of the expected amount. This is critical for several
2136         /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
2137         /// payment_preimage without having provided the full value and b) it avoids certain
2138         /// privacy-breaking recipient-probing attacks which may reveal payment activity to
2139         /// motivated attackers.
2140         ///
2141         /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
2142         /// set. Thus, for such payments we will claim any payments which do not under-pay.
2143         ///
2144         /// May panic if called except in response to a PaymentReceived event.
2145         pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<PaymentSecret>, expected_amount: u64) -> bool {
2146                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2147
2148                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2149
2150                 let mut channel_state = Some(self.channel_state.lock().unwrap());
2151                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
2152                 if let Some(mut sources) = removed_source {
2153                         assert!(!sources.is_empty());
2154
2155                         // If we are claiming an MPP payment, we have to take special care to ensure that each
2156                         // channel exists before claiming all of the payments (inside one lock).
2157                         // Note that channel existance is sufficient as we should always get a monitor update
2158                         // which will take care of the real HTLC claim enforcement.
2159                         //
2160                         // If we find an HTLC which we would need to claim but for which we do not have a
2161                         // channel, we will fail all parts of the MPP payment. While we could wait and see if
2162                         // the sender retries the already-failed path(s), it should be a pretty rare case where
2163                         // we got all the HTLCs and then a channel closed while we were waiting for the user to
2164                         // provide the preimage, so worrying too much about the optimal handling isn't worth
2165                         // it.
2166
2167                         let (is_mpp, mut valid_mpp) = if let &Some(ref data) = &sources[0].payment_data {
2168                                 assert!(payment_secret.is_some());
2169                                 (true, data.total_msat >= expected_amount)
2170                         } else {
2171                                 assert!(payment_secret.is_none());
2172                                 (false, false)
2173                         };
2174
2175                         for htlc in sources.iter() {
2176                                 if !is_mpp || !valid_mpp { break; }
2177                                 if let None = channel_state.as_ref().unwrap().short_to_id.get(&htlc.prev_hop.short_channel_id) {
2178                                         valid_mpp = false;
2179                                 }
2180                         }
2181
2182                         let mut errs = Vec::new();
2183                         let mut claimed_any_htlcs = false;
2184                         for htlc in sources.drain(..) {
2185                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2186                                 if (is_mpp && !valid_mpp) || (!is_mpp && (htlc.value < expected_amount || htlc.value > expected_amount * 2)) {
2187                                         let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2188                                         htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2189                                                 self.latest_block_height.load(Ordering::Acquire) as u32,
2190                                         ));
2191                                         self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2192                                                                          HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
2193                                                                          HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data });
2194                                 } else {
2195                                         match self.claim_funds_from_hop(channel_state.as_mut().unwrap(), htlc.prev_hop, payment_preimage) {
2196                                                 Err(Some(e)) => {
2197                                                         if let msgs::ErrorAction::IgnoreError = e.1.err.action {
2198                                                                 // We got a temporary failure updating monitor, but will claim the
2199                                                                 // HTLC when the monitor updating is restored (or on chain).
2200                                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", e.1.err.err);
2201                                                                 claimed_any_htlcs = true;
2202                                                         } else { errs.push(e); }
2203                                                 },
2204                                                 Err(None) if is_mpp => unreachable!("We already checked for channel existence, we can't fail here!"),
2205                                                 Err(None) => {
2206                                                         log_warn!(self.logger, "Channel we expected to claim an HTLC from was closed.");
2207                                                 },
2208                                                 Ok(()) => claimed_any_htlcs = true,
2209                                         }
2210                                 }
2211                         }
2212
2213                         // Now that we've done the entire above loop in one lock, we can handle any errors
2214                         // which were generated.
2215                         channel_state.take();
2216
2217                         for (counterparty_node_id, err) in errs.drain(..) {
2218                                 let res: Result<(), _> = Err(err);
2219                                 let _ = handle_error!(self, res, counterparty_node_id);
2220                         }
2221
2222                         claimed_any_htlcs
2223                 } else { false }
2224         }
2225
2226         fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
2227                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
2228                 let channel_state = &mut **channel_state_lock;
2229                 let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
2230                         Some(chan_id) => chan_id.clone(),
2231                         None => {
2232                                 return Err(None)
2233                         }
2234                 };
2235
2236                 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
2237                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2238                         match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
2239                                 Ok((msgs, monitor_option)) => {
2240                                         if let Some(monitor_update) = monitor_option {
2241                                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2242                                                         if was_frozen_for_monitor {
2243                                                                 assert!(msgs.is_none());
2244                                                         } else {
2245                                                                 return Err(Some((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, msgs.is_some()).unwrap_err())));
2246                                                         }
2247                                                 }
2248                                         }
2249                                         if let Some((msg, commitment_signed)) = msgs {
2250                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2251                                                         node_id: chan.get().get_counterparty_node_id(),
2252                                                         updates: msgs::CommitmentUpdate {
2253                                                                 update_add_htlcs: Vec::new(),
2254                                                                 update_fulfill_htlcs: vec![msg],
2255                                                                 update_fail_htlcs: Vec::new(),
2256                                                                 update_fail_malformed_htlcs: Vec::new(),
2257                                                                 update_fee: None,
2258                                                                 commitment_signed,
2259                                                         }
2260                                                 });
2261                                         }
2262                                         return Ok(())
2263                                 },
2264                                 Err(e) => {
2265                                         // TODO: Do something with e?
2266                                         // This should only occur if we are claiming an HTLC at the same time as the
2267                                         // HTLC is being failed (eg because a block is being connected and this caused
2268                                         // an HTLC to time out). This should, of course, only occur if the user is the
2269                                         // one doing the claiming (as it being a part of a peer claim would imply we're
2270                                         // about to lose funds) and only if the lock in claim_funds was dropped as a
2271                                         // previous HTLC was failed (thus not for an MPP payment).
2272                                         debug_assert!(false, "This shouldn't be reachable except in absurdly rare cases between monitor updates and HTLC timeouts: {:?}", e);
2273                                         return Err(None)
2274                                 },
2275                         }
2276                 } else { unreachable!(); }
2277         }
2278
2279         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2280                 match source {
2281                         HTLCSource::OutboundRoute { .. } => {
2282                                 mem::drop(channel_state_lock);
2283                                 let mut pending_events = self.pending_events.lock().unwrap();
2284                                 pending_events.push(events::Event::PaymentSent {
2285                                         payment_preimage
2286                                 });
2287                         },
2288                         HTLCSource::PreviousHopData(hop_data) => {
2289                                 let prev_outpoint = hop_data.outpoint;
2290                                 if let Err((counterparty_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
2291                                         Ok(()) => Ok(()),
2292                                         Err(None) => {
2293                                                 let preimage_update = ChannelMonitorUpdate {
2294                                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
2295                                                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
2296                                                                 payment_preimage: payment_preimage.clone(),
2297                                                         }],
2298                                                 };
2299                                                 // We update the ChannelMonitor on the backward link, after
2300                                                 // receiving an offchain preimage event from the forward link (the
2301                                                 // event being update_fulfill_htlc).
2302                                                 if let Err(e) = self.chain_monitor.update_channel(prev_outpoint, preimage_update) {
2303                                                         log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
2304                                                                    payment_preimage, e);
2305                                                 }
2306                                                 Ok(())
2307                                         },
2308                                         Err(Some(res)) => Err(res),
2309                                 } {
2310                                         mem::drop(channel_state_lock);
2311                                         let res: Result<(), _> = Err(err);
2312                                         let _ = handle_error!(self, res, counterparty_node_id);
2313                                 }
2314                         },
2315                 }
2316         }
2317
2318         /// Gets the node_id held by this ChannelManager
2319         pub fn get_our_node_id(&self) -> PublicKey {
2320                 self.our_network_pubkey.clone()
2321         }
2322
2323         /// Restores a single, given channel to normal operation after a
2324         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
2325         /// operation.
2326         ///
2327         /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
2328         /// fully committed in every copy of the given channels' ChannelMonitors.
2329         ///
2330         /// Note that there is no effect to calling with a highest_applied_update_id other than the
2331         /// current latest ChannelMonitorUpdate and one call to this function after multiple
2332         /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
2333         /// exists largely only to prevent races between this and concurrent update_monitor calls.
2334         ///
2335         /// Thus, the anticipated use is, at a high level:
2336         ///  1) You register a chain::Watch with this ChannelManager,
2337         ///  2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
2338         ///     said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
2339         ///     any time it cannot do so instantly,
2340         ///  3) update(s) are applied to each remote copy of a ChannelMonitor,
2341         ///  4) once all remote copies are updated, you call this function with the update_id that
2342         ///     completed, and once it is the latest the Channel will be re-enabled.
2343         pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
2344                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2345
2346                 let mut close_results = Vec::new();
2347                 let mut htlc_forwards = Vec::new();
2348                 let mut htlc_failures = Vec::new();
2349                 let mut pending_events = Vec::new();
2350
2351                 {
2352                         let mut channel_lock = self.channel_state.lock().unwrap();
2353                         let channel_state = &mut *channel_lock;
2354                         let short_to_id = &mut channel_state.short_to_id;
2355                         let pending_msg_events = &mut channel_state.pending_msg_events;
2356                         let channel = match channel_state.by_id.get_mut(&funding_txo.to_channel_id()) {
2357                                 Some(chan) => chan,
2358                                 None => return,
2359                         };
2360                         if !channel.is_awaiting_monitor_update() || channel.get_latest_monitor_update_id() != highest_applied_update_id {
2361                                 return;
2362                         }
2363
2364                         let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored(&self.logger);
2365                         if !pending_forwards.is_empty() {
2366                                 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), funding_txo.clone(), pending_forwards));
2367                         }
2368                         htlc_failures.append(&mut pending_failures);
2369
2370                         macro_rules! handle_cs { () => {
2371                                 if let Some(update) = commitment_update {
2372                                         pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2373                                                 node_id: channel.get_counterparty_node_id(),
2374                                                 updates: update,
2375                                         });
2376                                 }
2377                         } }
2378                         macro_rules! handle_raa { () => {
2379                                 if let Some(revoke_and_ack) = raa {
2380                                         pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2381                                                 node_id: channel.get_counterparty_node_id(),
2382                                                 msg: revoke_and_ack,
2383                                         });
2384                                 }
2385                         } }
2386                         match order {
2387                                 RAACommitmentOrder::CommitmentFirst => {
2388                                         handle_cs!();
2389                                         handle_raa!();
2390                                 },
2391                                 RAACommitmentOrder::RevokeAndACKFirst => {
2392                                         handle_raa!();
2393                                         handle_cs!();
2394                                 },
2395                         }
2396                         if needs_broadcast_safe {
2397                                 pending_events.push(events::Event::FundingBroadcastSafe {
2398                                         funding_txo: channel.get_funding_txo().unwrap(),
2399                                         user_channel_id: channel.get_user_id(),
2400                                 });
2401                         }
2402                         if let Some(msg) = funding_locked {
2403                                 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2404                                         node_id: channel.get_counterparty_node_id(),
2405                                         msg,
2406                                 });
2407                                 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2408                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2409                                                 node_id: channel.get_counterparty_node_id(),
2410                                                 msg: announcement_sigs,
2411                                         });
2412                                 }
2413                                 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2414                         }
2415                 }
2416
2417                 self.pending_events.lock().unwrap().append(&mut pending_events);
2418
2419                 for failure in htlc_failures.drain(..) {
2420                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2421                 }
2422                 self.forward_htlcs(&mut htlc_forwards[..]);
2423
2424                 for res in close_results.drain(..) {
2425                         self.finish_force_close_channel(res);
2426                 }
2427         }
2428
2429         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2430                 if msg.chain_hash != self.genesis_hash {
2431                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
2432                 }
2433
2434                 let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(), their_features, msg, 0, &self.default_configuration)
2435                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2436                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2437                 let channel_state = &mut *channel_state_lock;
2438                 match channel_state.by_id.entry(channel.channel_id()) {
2439                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
2440                         hash_map::Entry::Vacant(entry) => {
2441                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2442                                         node_id: counterparty_node_id.clone(),
2443                                         msg: channel.get_accept_channel(),
2444                                 });
2445                                 entry.insert(channel);
2446                         }
2447                 }
2448                 Ok(())
2449         }
2450
2451         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2452                 let (value, output_script, user_id) = {
2453                         let mut channel_lock = self.channel_state.lock().unwrap();
2454                         let channel_state = &mut *channel_lock;
2455                         match channel_state.by_id.entry(msg.temporary_channel_id) {
2456                                 hash_map::Entry::Occupied(mut chan) => {
2457                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2458                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2459                                         }
2460                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2461                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2462                                 },
2463                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2464                         }
2465                 };
2466                 let mut pending_events = self.pending_events.lock().unwrap();
2467                 pending_events.push(events::Event::FundingGenerationReady {
2468                         temporary_channel_id: msg.temporary_channel_id,
2469                         channel_value_satoshis: value,
2470                         output_script,
2471                         user_channel_id: user_id,
2472                 });
2473                 Ok(())
2474         }
2475
2476         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2477                 let ((funding_msg, monitor), mut chan) = {
2478                         let last_block_hash = *self.last_block_hash.read().unwrap();
2479                         let mut channel_lock = self.channel_state.lock().unwrap();
2480                         let channel_state = &mut *channel_lock;
2481                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2482                                 hash_map::Entry::Occupied(mut chan) => {
2483                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2484                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2485                                         }
2486                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg, last_block_hash, &self.logger), channel_state, chan), chan.remove())
2487                                 },
2488                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2489                         }
2490                 };
2491                 // Because we have exclusive ownership of the channel here we can release the channel_state
2492                 // lock before watch_channel
2493                 if let Err(e) = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
2494                         match e {
2495                                 ChannelMonitorUpdateErr::PermanentFailure => {
2496                                         // Note that we reply with the new channel_id in error messages if we gave up on the
2497                                         // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2498                                         // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2499                                         // any messages referencing a previously-closed channel anyway.
2500                                         // We do not do a force-close here as that would generate a monitor update for
2501                                         // a monitor that we didn't manage to store (and that we don't care about - we
2502                                         // don't respond with the funding_signed so the channel can never go on chain).
2503                                         let (_monitor_update, failed_htlcs) = chan.force_shutdown(true);
2504                                         assert!(failed_htlcs.is_empty());
2505                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
2506                                 },
2507                                 ChannelMonitorUpdateErr::TemporaryFailure => {
2508                                         // There's no problem signing a counterparty's funding transaction if our monitor
2509                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2510                                         // accepted payment from yet. We do, however, need to wait to send our funding_locked
2511                                         // until we have persisted our monitor.
2512                                         chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2513                                 },
2514                         }
2515                 }
2516                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2517                 let channel_state = &mut *channel_state_lock;
2518                 match channel_state.by_id.entry(funding_msg.channel_id) {
2519                         hash_map::Entry::Occupied(_) => {
2520                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
2521                         },
2522                         hash_map::Entry::Vacant(e) => {
2523                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2524                                         node_id: counterparty_node_id.clone(),
2525                                         msg: funding_msg,
2526                                 });
2527                                 e.insert(chan);
2528                         }
2529                 }
2530                 Ok(())
2531         }
2532
2533         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2534                 let (funding_txo, user_id) = {
2535                         let last_block_hash = *self.last_block_hash.read().unwrap();
2536                         let mut channel_lock = self.channel_state.lock().unwrap();
2537                         let channel_state = &mut *channel_lock;
2538                         match channel_state.by_id.entry(msg.channel_id) {
2539                                 hash_map::Entry::Occupied(mut chan) => {
2540                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2541                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2542                                         }
2543                                         let monitor = match chan.get_mut().funding_signed(&msg, last_block_hash, &self.logger) {
2544                                                 Ok(update) => update,
2545                                                 Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
2546                                         };
2547                                         if let Err(e) = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
2548                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2549                                         }
2550                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2551                                 },
2552                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2553                         }
2554                 };
2555                 let mut pending_events = self.pending_events.lock().unwrap();
2556                 pending_events.push(events::Event::FundingBroadcastSafe {
2557                         funding_txo,
2558                         user_channel_id: user_id,
2559                 });
2560                 Ok(())
2561         }
2562
2563         fn internal_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2564                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2565                 let channel_state = &mut *channel_state_lock;
2566                 match channel_state.by_id.entry(msg.channel_id) {
2567                         hash_map::Entry::Occupied(mut chan) => {
2568                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2569                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2570                                 }
2571                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2572                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2573                                         log_trace!(self.logger, "Sending announcement_signatures for {} in response to funding_locked", log_bytes!(chan.get().channel_id()));
2574                                         // If we see locking block before receiving remote funding_locked, we broadcast our
2575                                         // announcement_sigs at remote funding_locked reception. If we receive remote
2576                                         // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2577                                         // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2578                                         // the order of the events but our peer may not receive it due to disconnection. The specs
2579                                         // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2580                                         // connection in the future if simultaneous misses by both peers due to network/hardware
2581                                         // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2582                                         // to be received, from then sigs are going to be flood to the whole network.
2583                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2584                                                 node_id: counterparty_node_id.clone(),
2585                                                 msg: announcement_sigs,
2586                                         });
2587                                 }
2588                                 Ok(())
2589                         },
2590                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2591                 }
2592         }
2593
2594         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2595                 let (mut dropped_htlcs, chan_option) = {
2596                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2597                         let channel_state = &mut *channel_state_lock;
2598
2599                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2600                                 hash_map::Entry::Occupied(mut chan_entry) => {
2601                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2602                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2603                                         }
2604                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&self.fee_estimator, &their_features, &msg), channel_state, chan_entry);
2605                                         if let Some(msg) = shutdown {
2606                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2607                                                         node_id: counterparty_node_id.clone(),
2608                                                         msg,
2609                                                 });
2610                                         }
2611                                         if let Some(msg) = closing_signed {
2612                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2613                                                         node_id: counterparty_node_id.clone(),
2614                                                         msg,
2615                                                 });
2616                                         }
2617                                         if chan_entry.get().is_shutdown() {
2618                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2619                                                         channel_state.short_to_id.remove(&short_id);
2620                                                 }
2621                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2622                                         } else { (dropped_htlcs, None) }
2623                                 },
2624                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2625                         }
2626                 };
2627                 for htlc_source in dropped_htlcs.drain(..) {
2628                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2629                 }
2630                 if let Some(chan) = chan_option {
2631                         if let Ok(update) = self.get_channel_update(&chan) {
2632                                 let mut channel_state = self.channel_state.lock().unwrap();
2633                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2634                                         msg: update
2635                                 });
2636                         }
2637                 }
2638                 Ok(())
2639         }
2640
2641         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2642                 let (tx, chan_option) = {
2643                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2644                         let channel_state = &mut *channel_state_lock;
2645                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2646                                 hash_map::Entry::Occupied(mut chan_entry) => {
2647                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2648                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2649                                         }
2650                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), channel_state, chan_entry);
2651                                         if let Some(msg) = closing_signed {
2652                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2653                                                         node_id: counterparty_node_id.clone(),
2654                                                         msg,
2655                                                 });
2656                                         }
2657                                         if tx.is_some() {
2658                                                 // We're done with this channel, we've got a signed closing transaction and
2659                                                 // will send the closing_signed back to the remote peer upon return. This
2660                                                 // also implies there are no pending HTLCs left on the channel, so we can
2661                                                 // fully delete it from tracking (the channel monitor is still around to
2662                                                 // watch for old state broadcasts)!
2663                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2664                                                         channel_state.short_to_id.remove(&short_id);
2665                                                 }
2666                                                 (tx, Some(chan_entry.remove_entry().1))
2667                                         } else { (tx, None) }
2668                                 },
2669                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2670                         }
2671                 };
2672                 if let Some(broadcast_tx) = tx {
2673                         log_trace!(self.logger, "Broadcast onchain {}", log_tx!(broadcast_tx));
2674                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2675                 }
2676                 if let Some(chan) = chan_option {
2677                         if let Ok(update) = self.get_channel_update(&chan) {
2678                                 let mut channel_state = self.channel_state.lock().unwrap();
2679                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2680                                         msg: update
2681                                 });
2682                         }
2683                 }
2684                 Ok(())
2685         }
2686
2687         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2688                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2689                 //determine the state of the payment based on our response/if we forward anything/the time
2690                 //we take to respond. We should take care to avoid allowing such an attack.
2691                 //
2692                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2693                 //us repeatedly garbled in different ways, and compare our error messages, which are
2694                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2695                 //but we should prevent it anyway.
2696
2697                 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2698                 let channel_state = &mut *channel_state_lock;
2699
2700                 match channel_state.by_id.entry(msg.channel_id) {
2701                         hash_map::Entry::Occupied(mut chan) => {
2702                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2703                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2704                                 }
2705
2706                                 let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
2707                                         // Ensure error_code has the UPDATE flag set, since by default we send a
2708                                         // channel update along as part of failing the HTLC.
2709                                         assert!((error_code & 0x1000) != 0);
2710                                         // If the update_add is completely bogus, the call will Err and we will close,
2711                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2712                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2713                                         match pending_forward_info {
2714                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
2715                                                         let reason = if let Ok(upd) = self.get_channel_update(chan) {
2716                                                                 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &{
2717                                                                         let mut res = Vec::with_capacity(8 + 128);
2718                                                                         // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
2719                                                                         res.extend_from_slice(&byte_utils::be16_to_array(0));
2720                                                                         res.extend_from_slice(&upd.encode_with_len()[..]);
2721                                                                         res
2722                                                                 }[..])
2723                                                         } else {
2724                                                                 // The only case where we'd be unable to
2725                                                                 // successfully get a channel update is if the
2726                                                                 // channel isn't in the fully-funded state yet,
2727                                                                 // implying our counterparty is trying to route
2728                                                                 // payments over the channel back to themselves
2729                                                                 // (cause no one else should know the short_id
2730                                                                 // is a lightning channel yet). We should have
2731                                                                 // no problem just calling this
2732                                                                 // unknown_next_peer (0x4000|10).
2733                                                                 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, 0x4000|10, &[])
2734                                                         };
2735                                                         let msg = msgs::UpdateFailHTLC {
2736                                                                 channel_id: msg.channel_id,
2737                                                                 htlc_id: msg.htlc_id,
2738                                                                 reason
2739                                                         };
2740                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
2741                                                 },
2742                                                 _ => pending_forward_info
2743                                         }
2744                                 };
2745                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), channel_state, chan);
2746                         },
2747                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2748                 }
2749                 Ok(())
2750         }
2751
2752         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2753                 let mut channel_lock = self.channel_state.lock().unwrap();
2754                 let htlc_source = {
2755                         let channel_state = &mut *channel_lock;
2756                         match channel_state.by_id.entry(msg.channel_id) {
2757                                 hash_map::Entry::Occupied(mut chan) => {
2758                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2759                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2760                                         }
2761                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2762                                 },
2763                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2764                         }
2765                 };
2766                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2767                 Ok(())
2768         }
2769
2770         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2771                 let mut channel_lock = self.channel_state.lock().unwrap();
2772                 let channel_state = &mut *channel_lock;
2773                 match channel_state.by_id.entry(msg.channel_id) {
2774                         hash_map::Entry::Occupied(mut chan) => {
2775                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2776                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2777                                 }
2778                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2779                         },
2780                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2781                 }
2782                 Ok(())
2783         }
2784
2785         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2786                 let mut channel_lock = self.channel_state.lock().unwrap();
2787                 let channel_state = &mut *channel_lock;
2788                 match channel_state.by_id.entry(msg.channel_id) {
2789                         hash_map::Entry::Occupied(mut chan) => {
2790                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2791                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2792                                 }
2793                                 if (msg.failure_code & 0x8000) == 0 {
2794                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
2795                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
2796                                 }
2797                                 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);
2798                                 Ok(())
2799                         },
2800                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2801                 }
2802         }
2803
2804         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2805                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2806                 let channel_state = &mut *channel_state_lock;
2807                 match channel_state.by_id.entry(msg.channel_id) {
2808                         hash_map::Entry::Occupied(mut chan) => {
2809                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2810                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2811                                 }
2812                                 let (revoke_and_ack, commitment_signed, closing_signed, monitor_update) =
2813                                         match chan.get_mut().commitment_signed(&msg, &self.fee_estimator, &self.logger) {
2814                                                 Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan),
2815                                                 Err((Some(update), e)) => {
2816                                                         assert!(chan.get().is_awaiting_monitor_update());
2817                                                         let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update);
2818                                                         try_chan_entry!(self, Err(e), channel_state, chan);
2819                                                         unreachable!();
2820                                                 },
2821                                                 Ok(res) => res
2822                                         };
2823                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2824                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2825                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2826                                 }
2827                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2828                                         node_id: counterparty_node_id.clone(),
2829                                         msg: revoke_and_ack,
2830                                 });
2831                                 if let Some(msg) = commitment_signed {
2832                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2833                                                 node_id: counterparty_node_id.clone(),
2834                                                 updates: msgs::CommitmentUpdate {
2835                                                         update_add_htlcs: Vec::new(),
2836                                                         update_fulfill_htlcs: Vec::new(),
2837                                                         update_fail_htlcs: Vec::new(),
2838                                                         update_fail_malformed_htlcs: Vec::new(),
2839                                                         update_fee: None,
2840                                                         commitment_signed: msg,
2841                                                 },
2842                                         });
2843                                 }
2844                                 if let Some(msg) = closing_signed {
2845                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2846                                                 node_id: counterparty_node_id.clone(),
2847                                                 msg,
2848                                         });
2849                                 }
2850                                 Ok(())
2851                         },
2852                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2853                 }
2854         }
2855
2856         #[inline]
2857         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, Vec<(PendingHTLCInfo, u64)>)]) {
2858                 for &mut (prev_short_channel_id, prev_funding_outpoint, ref mut pending_forwards) in per_source_pending_forwards {
2859                         let mut forward_event = None;
2860                         if !pending_forwards.is_empty() {
2861                                 let mut channel_state = self.channel_state.lock().unwrap();
2862                                 if channel_state.forward_htlcs.is_empty() {
2863                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2864                                 }
2865                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2866                                         match channel_state.forward_htlcs.entry(match forward_info.routing {
2867                                                         PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
2868                                                         PendingHTLCRouting::Receive { .. } => 0,
2869                                         }) {
2870                                                 hash_map::Entry::Occupied(mut entry) => {
2871                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2872                                                                                                         prev_htlc_id, forward_info });
2873                                                 },
2874                                                 hash_map::Entry::Vacant(entry) => {
2875                                                         entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2876                                                                                                      prev_htlc_id, forward_info }));
2877                                                 }
2878                                         }
2879                                 }
2880                         }
2881                         match forward_event {
2882                                 Some(time) => {
2883                                         let mut pending_events = self.pending_events.lock().unwrap();
2884                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2885                                                 time_forwardable: time
2886                                         });
2887                                 }
2888                                 None => {},
2889                         }
2890                 }
2891         }
2892
2893         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2894                 let mut htlcs_to_fail = Vec::new();
2895                 let res = loop {
2896                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2897                         let channel_state = &mut *channel_state_lock;
2898                         match channel_state.by_id.entry(msg.channel_id) {
2899                                 hash_map::Entry::Occupied(mut chan) => {
2900                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2901                                                 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2902                                         }
2903                                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2904                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) =
2905                                                 break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan);
2906                                         htlcs_to_fail = htlcs_to_fail_in;
2907                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2908                                                 if was_frozen_for_monitor {
2909                                                         assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2910                                                         break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned()));
2911                                                 } else {
2912                                                         if let Err(e) = handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures) {
2913                                                                 break Err(e);
2914                                                         } else { unreachable!(); }
2915                                                 }
2916                                         }
2917                                         if let Some(updates) = commitment_update {
2918                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2919                                                         node_id: counterparty_node_id.clone(),
2920                                                         updates,
2921                                                 });
2922                                         }
2923                                         if let Some(msg) = closing_signed {
2924                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2925                                                         node_id: counterparty_node_id.clone(),
2926                                                         msg,
2927                                                 });
2928                                         }
2929                                         break Ok((pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"), chan.get().get_funding_txo().unwrap()))
2930                                 },
2931                                 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2932                         }
2933                 };
2934                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id);
2935                 match res {
2936                         Ok((pending_forwards, mut pending_failures, short_channel_id, channel_outpoint)) => {
2937                                 for failure in pending_failures.drain(..) {
2938                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2939                                 }
2940                                 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, pending_forwards)]);
2941                                 Ok(())
2942                         },
2943                         Err(e) => Err(e)
2944                 }
2945         }
2946
2947         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2948                 let mut channel_lock = self.channel_state.lock().unwrap();
2949                 let channel_state = &mut *channel_lock;
2950                 match channel_state.by_id.entry(msg.channel_id) {
2951                         hash_map::Entry::Occupied(mut chan) => {
2952                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2953                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2954                                 }
2955                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg), channel_state, chan);
2956                         },
2957                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2958                 }
2959                 Ok(())
2960         }
2961
2962         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2963                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2964                 let channel_state = &mut *channel_state_lock;
2965
2966                 match channel_state.by_id.entry(msg.channel_id) {
2967                         hash_map::Entry::Occupied(mut chan) => {
2968                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2969                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2970                                 }
2971                                 if !chan.get().is_usable() {
2972                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
2973                                 }
2974
2975                                 let our_node_id = self.get_our_node_id();
2976                                 let (announcement, our_bitcoin_sig) =
2977                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2978
2979                                 let were_node_one = announcement.node_id_1 == our_node_id;
2980                                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2981                                 {
2982                                         let their_node_key = if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 };
2983                                         let their_bitcoin_key = if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 };
2984                                         match (self.secp_ctx.verify(&msghash, &msg.node_signature, their_node_key),
2985                                                    self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, their_bitcoin_key)) {
2986                                                 (Err(e), _) => {
2987                                                         let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify node_signature: {:?}. Maybe using different node_secret for transport and routing msg? UnsignedChannelAnnouncement used for verification is {:?}. their_node_key is {:?}", e, &announcement, their_node_key));
2988                                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
2989                                                 },
2990                                                 (_, Err(e)) => {
2991                                                         let chan_err: ChannelError = ChannelError::Close(format!("Bad announcement_signatures. Failed to verify bitcoin_signature: {:?}. UnsignedChannelAnnouncement used for verification is {:?}. their_bitcoin_key is ({:?})", e, &announcement, their_bitcoin_key));
2992                                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
2993                                                 },
2994                                                 _ => {}
2995                                         }
2996                                 }
2997
2998                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2999
3000                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
3001                                         msg: msgs::ChannelAnnouncement {
3002                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
3003                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
3004                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
3005                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
3006                                                 contents: announcement,
3007                                         },
3008                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
3009                                 });
3010                         },
3011                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3012                 }
3013                 Ok(())
3014         }
3015
3016         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<(), MsgHandleErrInternal> {
3017                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3018                 let channel_state = &mut *channel_state_lock;
3019                 let chan_id = match channel_state.short_to_id.get(&msg.contents.short_channel_id) {
3020                         Some(chan_id) => chan_id.clone(),
3021                         None => {
3022                                 // It's not a local channel
3023                                 return Ok(())
3024                         }
3025                 };
3026                 match channel_state.by_id.entry(chan_id) {
3027                         hash_map::Entry::Occupied(mut chan) => {
3028                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3029                                         // TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
3030                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), chan_id));
3031                                 }
3032                                 try_chan_entry!(self, chan.get_mut().channel_update(&msg), channel_state, chan);
3033                         },
3034                         hash_map::Entry::Vacant(_) => unreachable!()
3035                 }
3036                 Ok(())
3037         }
3038
3039         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
3040                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3041                 let channel_state = &mut *channel_state_lock;
3042
3043                 match channel_state.by_id.entry(msg.channel_id) {
3044                         hash_map::Entry::Occupied(mut chan) => {
3045                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3046                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3047                                 }
3048                                 // Currently, we expect all holding cell update_adds to be dropped on peer
3049                                 // disconnect, so Channel's reestablish will never hand us any holding cell
3050                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
3051                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
3052                                 let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, mut order, shutdown) =
3053                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan);
3054                                 if let Some(monitor_update) = monitor_update_opt {
3055                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3056                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
3057                                                 // for the messages it returns, but if we're setting what messages to
3058                                                 // re-transmit on monitor update success, we need to make sure it is sane.
3059                                                 if revoke_and_ack.is_none() {
3060                                                         order = RAACommitmentOrder::CommitmentFirst;
3061                                                 }
3062                                                 if commitment_update.is_none() {
3063                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
3064                                                 }
3065                                                 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
3066                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
3067                                         }
3068                                 }
3069                                 if let Some(msg) = funding_locked {
3070                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3071                                                 node_id: counterparty_node_id.clone(),
3072                                                 msg
3073                                         });
3074                                 }
3075                                 macro_rules! send_raa { () => {
3076                                         if let Some(msg) = revoke_and_ack {
3077                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
3078                                                         node_id: counterparty_node_id.clone(),
3079                                                         msg
3080                                                 });
3081                                         }
3082                                 } }
3083                                 macro_rules! send_cu { () => {
3084                                         if let Some(updates) = commitment_update {
3085                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3086                                                         node_id: counterparty_node_id.clone(),
3087                                                         updates
3088                                                 });
3089                                         }
3090                                 } }
3091                                 match order {
3092                                         RAACommitmentOrder::RevokeAndACKFirst => {
3093                                                 send_raa!();
3094                                                 send_cu!();
3095                                         },
3096                                         RAACommitmentOrder::CommitmentFirst => {
3097                                                 send_cu!();
3098                                                 send_raa!();
3099                                         },
3100                                 }
3101                                 if let Some(msg) = shutdown {
3102                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
3103                                                 node_id: counterparty_node_id.clone(),
3104                                                 msg,
3105                                         });
3106                                 }
3107                                 Ok(())
3108                         },
3109                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3110                 }
3111         }
3112
3113         /// Begin Update fee process. Allowed only on an outbound channel.
3114         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
3115         /// PeerManager::process_events afterwards.
3116         /// Note: This API is likely to change!
3117         /// (C-not exported) Cause its doc(hidden) anyway
3118         #[doc(hidden)]
3119         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
3120                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3121                 let counterparty_node_id;
3122                 let err: Result<(), _> = loop {
3123                         let mut channel_state_lock = self.channel_state.lock().unwrap();
3124                         let channel_state = &mut *channel_state_lock;
3125
3126                         match channel_state.by_id.entry(channel_id) {
3127                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: format!("Failed to find corresponding channel for id {}", channel_id.to_hex())}),
3128                                 hash_map::Entry::Occupied(mut chan) => {
3129                                         if !chan.get().is_outbound() {
3130                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel".to_owned()});
3131                                         }
3132                                         if chan.get().is_awaiting_monitor_update() {
3133                                                 return Err(APIError::MonitorUpdateFailed);
3134                                         }
3135                                         if !chan.get().is_live() {
3136                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected".to_owned()});
3137                                         }
3138                                         counterparty_node_id = chan.get().get_counterparty_node_id();
3139                                         if let Some((update_fee, commitment_signed, monitor_update)) =
3140                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan)
3141                                         {
3142                                                 if let Err(_e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3143                                                         unimplemented!();
3144                                                 }
3145                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3146                                                         node_id: chan.get().get_counterparty_node_id(),
3147                                                         updates: msgs::CommitmentUpdate {
3148                                                                 update_add_htlcs: Vec::new(),
3149                                                                 update_fulfill_htlcs: Vec::new(),
3150                                                                 update_fail_htlcs: Vec::new(),
3151                                                                 update_fail_malformed_htlcs: Vec::new(),
3152                                                                 update_fee: Some(update_fee),
3153                                                                 commitment_signed,
3154                                                         },
3155                                                 });
3156                                         }
3157                                 },
3158                         }
3159                         return Ok(())
3160                 };
3161
3162                 match handle_error!(self, err, counterparty_node_id) {
3163                         Ok(_) => unreachable!(),
3164                         Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
3165                 }
3166         }
3167
3168         /// Process pending events from the `chain::Watch`.
3169         fn process_pending_monitor_events(&self) {
3170                 let mut failed_channels = Vec::new();
3171                 {
3172                         for monitor_event in self.chain_monitor.release_pending_monitor_events() {
3173                                 match monitor_event {
3174                                         MonitorEvent::HTLCEvent(htlc_update) => {
3175                                                 if let Some(preimage) = htlc_update.payment_preimage {
3176                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
3177                                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3178                                                 } else {
3179                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
3180                                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
3181                                                 }
3182                                         },
3183                                         MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
3184                                                 let mut channel_lock = self.channel_state.lock().unwrap();
3185                                                 let channel_state = &mut *channel_lock;
3186                                                 let by_id = &mut channel_state.by_id;
3187                                                 let short_to_id = &mut channel_state.short_to_id;
3188                                                 let pending_msg_events = &mut channel_state.pending_msg_events;
3189                                                 if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
3190                                                         if let Some(short_id) = chan.get_short_channel_id() {
3191                                                                 short_to_id.remove(&short_id);
3192                                                         }
3193                                                         failed_channels.push(chan.force_shutdown(false));
3194                                                         if let Ok(update) = self.get_channel_update(&chan) {
3195                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3196                                                                         msg: update
3197                                                                 });
3198                                                         }
3199                                                 }
3200                                         },
3201                                 }
3202                         }
3203                 }
3204
3205                 for failure in failed_channels.drain(..) {
3206                         self.finish_force_close_channel(failure);
3207                 }
3208         }
3209
3210         /// Handle a list of channel failures during a block_connected or block_disconnected call,
3211         /// pushing the channel monitor update (if any) to the background events queue and removing the
3212         /// Channel object.
3213         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
3214                 for mut failure in failed_channels.drain(..) {
3215                         // Either a commitment transactions has been confirmed on-chain or
3216                         // Channel::block_disconnected detected that the funding transaction has been
3217                         // reorganized out of the main chain.
3218                         // We cannot broadcast our latest local state via monitor update (as
3219                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
3220                         // so we track the update internally and handle it when the user next calls
3221                         // timer_chan_freshness_every_min, guaranteeing we're running normally.
3222                         if let Some((funding_txo, update)) = failure.0.take() {
3223                                 assert_eq!(update.updates.len(), 1);
3224                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
3225                                         assert!(should_broadcast);
3226                                 } else { unreachable!(); }
3227                                 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
3228                         }
3229                         self.finish_force_close_channel(failure);
3230                 }
3231         }
3232 }
3233
3234 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
3235         where M::Target: chain::Watch<Signer>,
3236         T::Target: BroadcasterInterface,
3237         K::Target: KeysInterface<Signer = Signer>,
3238         F::Target: FeeEstimator,
3239                                 L::Target: Logger,
3240 {
3241         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
3242                 //TODO: This behavior should be documented. It's non-intuitive that we query
3243                 // ChannelMonitors when clearing other events.
3244                 self.process_pending_monitor_events();
3245
3246                 let mut ret = Vec::new();
3247                 let mut channel_state = self.channel_state.lock().unwrap();
3248                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
3249                 ret
3250         }
3251 }
3252
3253 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
3254         where M::Target: chain::Watch<Signer>,
3255         T::Target: BroadcasterInterface,
3256         K::Target: KeysInterface<Signer = Signer>,
3257         F::Target: FeeEstimator,
3258                                 L::Target: Logger,
3259 {
3260         fn get_and_clear_pending_events(&self) -> Vec<Event> {
3261                 //TODO: This behavior should be documented. It's non-intuitive that we query
3262                 // ChannelMonitors when clearing other events.
3263                 self.process_pending_monitor_events();
3264
3265                 let mut ret = Vec::new();
3266                 let mut pending_events = self.pending_events.lock().unwrap();
3267                 mem::swap(&mut ret, &mut *pending_events);
3268                 ret
3269         }
3270 }
3271
3272 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Listen for ChannelManager<Signer, M, T, K, F, L>
3273 where
3274         M::Target: chain::Watch<Signer>,
3275         T::Target: BroadcasterInterface,
3276         K::Target: KeysInterface<Signer = Signer>,
3277         F::Target: FeeEstimator,
3278         L::Target: Logger,
3279 {
3280         fn block_connected(&self, block: &Block, height: u32) {
3281                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
3282                 ChannelManager::block_connected(self, &block.header, &txdata, height);
3283         }
3284
3285         fn block_disconnected(&self, header: &BlockHeader, _height: u32) {
3286                 ChannelManager::block_disconnected(self, header);
3287         }
3288 }
3289
3290 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
3291         where M::Target: chain::Watch<Signer>,
3292         T::Target: BroadcasterInterface,
3293         K::Target: KeysInterface<Signer = Signer>,
3294         F::Target: FeeEstimator,
3295         L::Target: Logger,
3296 {
3297         /// Updates channel state based on transactions seen in a connected block.
3298         pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3299                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3300                 // during initialization prior to the chain_monitor being fully configured in some cases.
3301                 // See the docs for `ChannelManagerReadArgs` for more.
3302                 let block_hash = header.block_hash();
3303                 log_trace!(self.logger, "Block {} at height {} connected", block_hash, height);
3304
3305                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3306
3307                 assert_eq!(*self.last_block_hash.read().unwrap(), header.prev_blockhash,
3308                         "Blocks must be connected in chain-order - the connected header must build on the last connected header");
3309                 assert_eq!(self.latest_block_height.load(Ordering::Acquire) as u64, height as u64 - 1,
3310                         "Blocks must be connected in chain-order - the connected header must build on the last connected header");
3311                 self.latest_block_height.store(height as usize, Ordering::Release);
3312                 *self.last_block_hash.write().unwrap() = block_hash;
3313
3314                 let mut failed_channels = Vec::new();
3315                 let mut timed_out_htlcs = Vec::new();
3316                 {
3317                         let mut channel_lock = self.channel_state.lock().unwrap();
3318                         let channel_state = &mut *channel_lock;
3319                         let short_to_id = &mut channel_state.short_to_id;
3320                         let pending_msg_events = &mut channel_state.pending_msg_events;
3321                         channel_state.by_id.retain(|_, channel| {
3322                                 let res = channel.block_connected(header, txdata, height);
3323                                 if let Ok((chan_res, mut timed_out_pending_htlcs)) = res {
3324                                         for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
3325                                                 let chan_update = self.get_channel_update(&channel).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
3326                                                 timed_out_htlcs.push((source, payment_hash,  HTLCFailReason::Reason {
3327                                                         failure_code: 0x1000 | 14, // expiry_too_soon, or at least it is now
3328                                                         data: chan_update,
3329                                                 }));
3330                                         }
3331                                         if let Some(funding_locked) = chan_res {
3332                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3333                                                         node_id: channel.get_counterparty_node_id(),
3334                                                         msg: funding_locked,
3335                                                 });
3336                                                 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
3337                                                         log_trace!(self.logger, "Sending funding_locked and announcement_signatures for {}", log_bytes!(channel.channel_id()));
3338                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3339                                                                 node_id: channel.get_counterparty_node_id(),
3340                                                                 msg: announcement_sigs,
3341                                                         });
3342                                                 } else {
3343                                                         log_trace!(self.logger, "Sending funding_locked WITHOUT announcement_signatures for {}", log_bytes!(channel.channel_id()));
3344                                                 }
3345                                                 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
3346                                         }
3347                                 } else if let Err(e) = res {
3348                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
3349                                                 node_id: channel.get_counterparty_node_id(),
3350                                                 action: msgs::ErrorAction::SendErrorMessage { msg: e },
3351                                         });
3352                                         return false;
3353                                 }
3354                                 if let Some(funding_txo) = channel.get_funding_txo() {
3355                                         for &(_, tx) in txdata.iter() {
3356                                                 for inp in tx.input.iter() {
3357                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
3358                                                                 log_trace!(self.logger, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
3359                                                                 if let Some(short_id) = channel.get_short_channel_id() {
3360                                                                         short_to_id.remove(&short_id);
3361                                                                 }
3362                                                                 // It looks like our counterparty went on-chain. Close the channel.
3363                                                                 failed_channels.push(channel.force_shutdown(true));
3364                                                                 if let Ok(update) = self.get_channel_update(&channel) {
3365                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3366                                                                                 msg: update
3367                                                                         });
3368                                                                 }
3369                                                                 return false;
3370                                                         }
3371                                                 }
3372                                         }
3373                                 }
3374                                 true
3375                         });
3376
3377                         channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3378                                 htlcs.retain(|htlc| {
3379                                         // If height is approaching the number of blocks we think it takes us to get
3380                                         // our commitment transaction confirmed before the HTLC expires, plus the
3381                                         // number of blocks we generally consider it to take to do a commitment update,
3382                                         // just give up on it and fail the HTLC.
3383                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3384                                                 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3385                                                 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3386                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3387                                                         failure_code: 0x4000 | 15,
3388                                                         data: htlc_msat_height_data
3389                                                 }));
3390                                                 false
3391                                         } else { true }
3392                                 });
3393                                 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3394                         });
3395                 }
3396
3397                 self.handle_init_event_channel_failures(failed_channels);
3398
3399                 for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3400                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3401                 }
3402
3403                 loop {
3404                         // Update last_node_announcement_serial to be the max of its current value and the
3405                         // block timestamp. This should keep us close to the current time without relying on
3406                         // having an explicit local time source.
3407                         // Just in case we end up in a race, we loop until we either successfully update
3408                         // last_node_announcement_serial or decide we don't need to.
3409                         let old_serial = self.last_node_announcement_serial.load(Ordering::Acquire);
3410                         if old_serial >= header.time as usize { break; }
3411                         if self.last_node_announcement_serial.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
3412                                 break;
3413                         }
3414                 }
3415         }
3416
3417         /// Updates channel state based on a disconnected block.
3418         ///
3419         /// If necessary, the channel may be force-closed without letting the counterparty participate
3420         /// in the shutdown.
3421         pub fn block_disconnected(&self, header: &BlockHeader) {
3422                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3423                 // during initialization prior to the chain_monitor being fully configured in some cases.
3424                 // See the docs for `ChannelManagerReadArgs` for more.
3425                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3426
3427                 assert_eq!(*self.last_block_hash.read().unwrap(), header.block_hash(),
3428                         "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
3429                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
3430                 *self.last_block_hash.write().unwrap() = header.prev_blockhash;
3431
3432                 let mut failed_channels = Vec::new();
3433                 {
3434                         let mut channel_lock = self.channel_state.lock().unwrap();
3435                         let channel_state = &mut *channel_lock;
3436                         let short_to_id = &mut channel_state.short_to_id;
3437                         let pending_msg_events = &mut channel_state.pending_msg_events;
3438                         channel_state.by_id.retain(|_,  v| {
3439                                 if v.block_disconnected(header) {
3440                                         if let Some(short_id) = v.get_short_channel_id() {
3441                                                 short_to_id.remove(&short_id);
3442                                         }
3443                                         failed_channels.push(v.force_shutdown(true));
3444                                         if let Ok(update) = self.get_channel_update(&v) {
3445                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3446                                                         msg: update
3447                                                 });
3448                                         }
3449                                         false
3450                                 } else {
3451                                         true
3452                                 }
3453                         });
3454                 }
3455
3456                 self.handle_init_event_channel_failures(failed_channels);
3457         }
3458
3459         /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
3460         /// indicating whether persistence is necessary. Only one listener on
3461         /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3462         /// up.
3463         /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
3464         #[cfg(any(test, feature = "allow_wallclock_use"))]
3465         pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
3466                 self.persistence_notifier.wait_timeout(max_wait)
3467         }
3468
3469         /// Blocks until ChannelManager needs to be persisted. Only one listener on
3470         /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3471         /// up.
3472         pub fn await_persistable_update(&self) {
3473                 self.persistence_notifier.wait()
3474         }
3475
3476         #[cfg(any(test, feature = "_test_utils"))]
3477         pub fn get_persistence_condvar_value(&self) -> bool {
3478                 let mutcond = &self.persistence_notifier.persistence_lock;
3479                 let &(ref mtx, _) = mutcond;
3480                 let guard = mtx.lock().unwrap();
3481                 *guard
3482         }
3483 }
3484
3485 impl<Signer: Sign, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
3486         ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
3487         where M::Target: chain::Watch<Signer>,
3488         T::Target: BroadcasterInterface,
3489         K::Target: KeysInterface<Signer = Signer>,
3490         F::Target: FeeEstimator,
3491         L::Target: Logger,
3492 {
3493         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
3494                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3495                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3496         }
3497
3498         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
3499                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3500                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3501         }
3502
3503         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
3504                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3505                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
3506         }
3507
3508         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
3509                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3510                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
3511         }
3512
3513         fn handle_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) {
3514                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3515                 let _ = handle_error!(self, self.internal_funding_locked(counterparty_node_id, msg), *counterparty_node_id);
3516         }
3517
3518         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
3519                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3520                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
3521         }
3522
3523         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
3524                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3525                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
3526         }
3527
3528         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
3529                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3530                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
3531         }
3532
3533         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
3534                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3535                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
3536         }
3537
3538         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
3539                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3540                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
3541         }
3542
3543         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
3544                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3545                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
3546         }
3547
3548         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
3549                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3550                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
3551         }
3552
3553         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
3554                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3555                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
3556         }
3557
3558         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
3559                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3560                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
3561         }
3562
3563         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
3564                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3565                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
3566         }
3567
3568         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
3569                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3570                 let _ = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id);
3571         }
3572
3573         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
3574                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3575                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
3576         }
3577
3578         fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
3579                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3580                 let mut failed_channels = Vec::new();
3581                 let mut failed_payments = Vec::new();
3582                 let mut no_channels_remain = true;
3583                 {
3584                         let mut channel_state_lock = self.channel_state.lock().unwrap();
3585                         let channel_state = &mut *channel_state_lock;
3586                         let short_to_id = &mut channel_state.short_to_id;
3587                         let pending_msg_events = &mut channel_state.pending_msg_events;
3588                         if no_connection_possible {
3589                                 log_debug!(self.logger, "Failing all channels with {} due to no_connection_possible", log_pubkey!(counterparty_node_id));
3590                                 channel_state.by_id.retain(|_, chan| {
3591                                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3592                                                 if let Some(short_id) = chan.get_short_channel_id() {
3593                                                         short_to_id.remove(&short_id);
3594                                                 }
3595                                                 failed_channels.push(chan.force_shutdown(true));
3596                                                 if let Ok(update) = self.get_channel_update(&chan) {
3597                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3598                                                                 msg: update
3599                                                         });
3600                                                 }
3601                                                 false
3602                                         } else {
3603                                                 true
3604                                         }
3605                                 });
3606                         } else {
3607                                 log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(counterparty_node_id));
3608                                 channel_state.by_id.retain(|_, chan| {
3609                                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3610                                                 // Note that currently on channel reestablish we assert that there are no
3611                                                 // holding cell add-HTLCs, so if in the future we stop removing uncommitted HTLCs
3612                                                 // on peer disconnect here, there will need to be corresponding changes in
3613                                                 // reestablish logic.
3614                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
3615                                                 chan.to_disabled_marked();
3616                                                 if !failed_adds.is_empty() {
3617                                                         let chan_update = self.get_channel_update(&chan).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
3618                                                         failed_payments.push((chan_update, failed_adds));
3619                                                 }
3620                                                 if chan.is_shutdown() {
3621                                                         if let Some(short_id) = chan.get_short_channel_id() {
3622                                                                 short_to_id.remove(&short_id);
3623                                                         }
3624                                                         return false;
3625                                                 } else {
3626                                                         no_channels_remain = false;
3627                                                 }
3628                                         }
3629                                         true
3630                                 })
3631                         }
3632                         pending_msg_events.retain(|msg| {
3633                                 match msg {
3634                                         &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != counterparty_node_id,
3635                                         &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != counterparty_node_id,
3636                                         &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != counterparty_node_id,
3637                                         &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3638                                         &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != counterparty_node_id,
3639                                         &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != counterparty_node_id,
3640                                         &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != counterparty_node_id,
3641                                         &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != counterparty_node_id,
3642                                         &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3643                                         &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != counterparty_node_id,
3644                                         &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
3645                                         &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3646                                         &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3647                                         &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3648                                         &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
3649                                         &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3650                                         &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
3651                                         &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
3652                                         &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
3653                                 }
3654                         });
3655                 }
3656                 if no_channels_remain {
3657                         self.per_peer_state.write().unwrap().remove(counterparty_node_id);
3658                 }
3659
3660                 for failure in failed_channels.drain(..) {
3661                         self.finish_force_close_channel(failure);
3662                 }
3663                 for (chan_update, mut htlc_sources) in failed_payments {
3664                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3665                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3666                         }
3667                 }
3668         }
3669
3670         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) {
3671                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
3672
3673                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3674
3675                 {
3676                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
3677                         match peer_state_lock.entry(counterparty_node_id.clone()) {
3678                                 hash_map::Entry::Vacant(e) => {
3679                                         e.insert(Mutex::new(PeerState {
3680                                                 latest_features: init_msg.features.clone(),
3681                                         }));
3682                                 },
3683                                 hash_map::Entry::Occupied(e) => {
3684                                         e.get().lock().unwrap().latest_features = init_msg.features.clone();
3685                                 },
3686                         }
3687                 }
3688
3689                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3690                 let channel_state = &mut *channel_state_lock;
3691                 let pending_msg_events = &mut channel_state.pending_msg_events;
3692                 channel_state.by_id.retain(|_, chan| {
3693                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3694                                 if !chan.have_received_message() {
3695                                         // If we created this (outbound) channel while we were disconnected from the
3696                                         // peer we probably failed to send the open_channel message, which is now
3697                                         // lost. We can't have had anything pending related to this channel, so we just
3698                                         // drop it.
3699                                         false
3700                                 } else {
3701                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3702                                                 node_id: chan.get_counterparty_node_id(),
3703                                                 msg: chan.get_channel_reestablish(&self.logger),
3704                                         });
3705                                         true
3706                                 }
3707                         } else { true }
3708                 });
3709                 //TODO: Also re-broadcast announcement_signatures
3710         }
3711
3712         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3713                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3714
3715                 if msg.channel_id == [0; 32] {
3716                         for chan in self.list_channels() {
3717                                 if chan.remote_network_id == *counterparty_node_id {
3718                                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3719                                         let _ = self.force_close_channel_with_peer(&chan.channel_id, Some(counterparty_node_id));
3720                                 }
3721                         }
3722                 } else {
3723                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3724                         let _ = self.force_close_channel_with_peer(&msg.channel_id, Some(counterparty_node_id));
3725                 }
3726         }
3727 }
3728
3729 /// Used to signal to the ChannelManager persister that the manager needs to be re-persisted to
3730 /// disk/backups, through `await_persistable_update_timeout` and `await_persistable_update`.
3731 struct PersistenceNotifier {
3732         /// Users won't access the persistence_lock directly, but rather wait on its bool using
3733         /// `wait_timeout` and `wait`.
3734         persistence_lock: (Mutex<bool>, Condvar),
3735 }
3736
3737 impl PersistenceNotifier {
3738         fn new() -> Self {
3739                 Self {
3740                         persistence_lock: (Mutex::new(false), Condvar::new()),
3741                 }
3742         }
3743
3744         fn wait(&self) {
3745                 loop {
3746                         let &(ref mtx, ref cvar) = &self.persistence_lock;
3747                         let mut guard = mtx.lock().unwrap();
3748                         guard = cvar.wait(guard).unwrap();
3749                         let result = *guard;
3750                         if result {
3751                                 *guard = false;
3752                                 return
3753                         }
3754                 }
3755         }
3756
3757         #[cfg(any(test, feature = "allow_wallclock_use"))]
3758         fn wait_timeout(&self, max_wait: Duration) -> bool {
3759                 let current_time = Instant::now();
3760                 loop {
3761                         let &(ref mtx, ref cvar) = &self.persistence_lock;
3762                         let mut guard = mtx.lock().unwrap();
3763                         guard = cvar.wait_timeout(guard, max_wait).unwrap().0;
3764                         // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
3765                         // desired wait time has actually passed, and if not then restart the loop with a reduced wait
3766                         // time. Note that this logic can be highly simplified through the use of
3767                         // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
3768                         // 1.42.0.
3769                         let elapsed = current_time.elapsed();
3770                         let result = *guard;
3771                         if result || elapsed >= max_wait {
3772                                 *guard = false;
3773                                 return result;
3774                         }
3775                         match max_wait.checked_sub(elapsed) {
3776                                 None => return result,
3777                                 Some(_) => continue
3778                         }
3779                 }
3780         }
3781
3782         // Signal to the ChannelManager persister that there are updates necessitating persisting to disk.
3783         fn notify(&self) {
3784                 let &(ref persist_mtx, ref cnd) = &self.persistence_lock;
3785                 let mut persistence_lock = persist_mtx.lock().unwrap();
3786                 *persistence_lock = true;
3787                 mem::drop(persistence_lock);
3788                 cnd.notify_all();
3789         }
3790 }
3791
3792 const SERIALIZATION_VERSION: u8 = 1;
3793 const MIN_SERIALIZATION_VERSION: u8 = 1;
3794
3795 impl Writeable for PendingHTLCInfo {
3796         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3797                 match &self.routing {
3798                         &PendingHTLCRouting::Forward { ref onion_packet, ref short_channel_id } => {
3799                                 0u8.write(writer)?;
3800                                 onion_packet.write(writer)?;
3801                                 short_channel_id.write(writer)?;
3802                         },
3803                         &PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
3804                                 1u8.write(writer)?;
3805                                 payment_data.write(writer)?;
3806                                 incoming_cltv_expiry.write(writer)?;
3807                         },
3808                 }
3809                 self.incoming_shared_secret.write(writer)?;
3810                 self.payment_hash.write(writer)?;
3811                 self.amt_to_forward.write(writer)?;
3812                 self.outgoing_cltv_value.write(writer)?;
3813                 Ok(())
3814         }
3815 }
3816
3817 impl Readable for PendingHTLCInfo {
3818         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3819                 Ok(PendingHTLCInfo {
3820                         routing: match Readable::read(reader)? {
3821                                 0u8 => PendingHTLCRouting::Forward {
3822                                         onion_packet: Readable::read(reader)?,
3823                                         short_channel_id: Readable::read(reader)?,
3824                                 },
3825                                 1u8 => PendingHTLCRouting::Receive {
3826                                         payment_data: Readable::read(reader)?,
3827                                         incoming_cltv_expiry: Readable::read(reader)?,
3828                                 },
3829                                 _ => return Err(DecodeError::InvalidValue),
3830                         },
3831                         incoming_shared_secret: Readable::read(reader)?,
3832                         payment_hash: Readable::read(reader)?,
3833                         amt_to_forward: Readable::read(reader)?,
3834                         outgoing_cltv_value: Readable::read(reader)?,
3835                 })
3836         }
3837 }
3838
3839 impl Writeable for HTLCFailureMsg {
3840         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3841                 match self {
3842                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3843                                 0u8.write(writer)?;
3844                                 fail_msg.write(writer)?;
3845                         },
3846                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3847                                 1u8.write(writer)?;
3848                                 fail_msg.write(writer)?;
3849                         }
3850                 }
3851                 Ok(())
3852         }
3853 }
3854
3855 impl Readable for HTLCFailureMsg {
3856         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3857                 match <u8 as Readable>::read(reader)? {
3858                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3859                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3860                         _ => Err(DecodeError::InvalidValue),
3861                 }
3862         }
3863 }
3864
3865 impl Writeable for PendingHTLCStatus {
3866         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3867                 match self {
3868                         &PendingHTLCStatus::Forward(ref forward_info) => {
3869                                 0u8.write(writer)?;
3870                                 forward_info.write(writer)?;
3871                         },
3872                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3873                                 1u8.write(writer)?;
3874                                 fail_msg.write(writer)?;
3875                         }
3876                 }
3877                 Ok(())
3878         }
3879 }
3880
3881 impl Readable for PendingHTLCStatus {
3882         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3883                 match <u8 as Readable>::read(reader)? {
3884                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3885                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3886                         _ => Err(DecodeError::InvalidValue),
3887                 }
3888         }
3889 }
3890
3891 impl_writeable!(HTLCPreviousHopData, 0, {
3892         short_channel_id,
3893         outpoint,
3894         htlc_id,
3895         incoming_packet_shared_secret
3896 });
3897
3898 impl_writeable!(ClaimableHTLC, 0, {
3899         prev_hop,
3900         value,
3901         payment_data,
3902         cltv_expiry
3903 });
3904
3905 impl Writeable for HTLCSource {
3906         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3907                 match self {
3908                         &HTLCSource::PreviousHopData(ref hop_data) => {
3909                                 0u8.write(writer)?;
3910                                 hop_data.write(writer)?;
3911                         },
3912                         &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } => {
3913                                 1u8.write(writer)?;
3914                                 path.write(writer)?;
3915                                 session_priv.write(writer)?;
3916                                 first_hop_htlc_msat.write(writer)?;
3917                         }
3918                 }
3919                 Ok(())
3920         }
3921 }
3922
3923 impl Readable for HTLCSource {
3924         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3925                 match <u8 as Readable>::read(reader)? {
3926                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3927                         1 => Ok(HTLCSource::OutboundRoute {
3928                                 path: Readable::read(reader)?,
3929                                 session_priv: Readable::read(reader)?,
3930                                 first_hop_htlc_msat: Readable::read(reader)?,
3931                         }),
3932                         _ => Err(DecodeError::InvalidValue),
3933                 }
3934         }
3935 }
3936
3937 impl Writeable for HTLCFailReason {
3938         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3939                 match self {
3940                         &HTLCFailReason::LightningError { ref err } => {
3941                                 0u8.write(writer)?;
3942                                 err.write(writer)?;
3943                         },
3944                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3945                                 1u8.write(writer)?;
3946                                 failure_code.write(writer)?;
3947                                 data.write(writer)?;
3948                         }
3949                 }
3950                 Ok(())
3951         }
3952 }
3953
3954 impl Readable for HTLCFailReason {
3955         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3956                 match <u8 as Readable>::read(reader)? {
3957                         0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3958                         1 => Ok(HTLCFailReason::Reason {
3959                                 failure_code: Readable::read(reader)?,
3960                                 data: Readable::read(reader)?,
3961                         }),
3962                         _ => Err(DecodeError::InvalidValue),
3963                 }
3964         }
3965 }
3966
3967 impl Writeable for HTLCForwardInfo {
3968         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3969                 match self {
3970                         &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_funding_outpoint, ref prev_htlc_id, ref forward_info } => {
3971                                 0u8.write(writer)?;
3972                                 prev_short_channel_id.write(writer)?;
3973                                 prev_funding_outpoint.write(writer)?;
3974                                 prev_htlc_id.write(writer)?;
3975                                 forward_info.write(writer)?;
3976                         },
3977                         &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
3978                                 1u8.write(writer)?;
3979                                 htlc_id.write(writer)?;
3980                                 err_packet.write(writer)?;
3981                         },
3982                 }
3983                 Ok(())
3984         }
3985 }
3986
3987 impl Readable for HTLCForwardInfo {
3988         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
3989                 match <u8 as Readable>::read(reader)? {
3990                         0 => Ok(HTLCForwardInfo::AddHTLC {
3991                                 prev_short_channel_id: Readable::read(reader)?,
3992                                 prev_funding_outpoint: Readable::read(reader)?,
3993                                 prev_htlc_id: Readable::read(reader)?,
3994                                 forward_info: Readable::read(reader)?,
3995                         }),
3996                         1 => Ok(HTLCForwardInfo::FailHTLC {
3997                                 htlc_id: Readable::read(reader)?,
3998                                 err_packet: Readable::read(reader)?,
3999                         }),
4000                         _ => Err(DecodeError::InvalidValue),
4001                 }
4002         }
4003 }
4004
4005 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
4006         where M::Target: chain::Watch<Signer>,
4007         T::Target: BroadcasterInterface,
4008         K::Target: KeysInterface<Signer = Signer>,
4009         F::Target: FeeEstimator,
4010         L::Target: Logger,
4011 {
4012         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4013                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
4014
4015                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
4016                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
4017
4018                 self.genesis_hash.write(writer)?;
4019                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
4020                 self.last_block_hash.read().unwrap().write(writer)?;
4021
4022                 let channel_state = self.channel_state.lock().unwrap();
4023                 let mut unfunded_channels = 0;
4024                 for (_, channel) in channel_state.by_id.iter() {
4025                         if !channel.is_funding_initiated() {
4026                                 unfunded_channels += 1;
4027                         }
4028                 }
4029                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
4030                 for (_, channel) in channel_state.by_id.iter() {
4031                         if channel.is_funding_initiated() {
4032                                 channel.write(writer)?;
4033                         }
4034                 }
4035
4036                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
4037                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
4038                         short_channel_id.write(writer)?;
4039                         (pending_forwards.len() as u64).write(writer)?;
4040                         for forward in pending_forwards {
4041                                 forward.write(writer)?;
4042                         }
4043                 }
4044
4045                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
4046                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
4047                         payment_hash.write(writer)?;
4048                         (previous_hops.len() as u64).write(writer)?;
4049                         for htlc in previous_hops.iter() {
4050                                 htlc.write(writer)?;
4051                         }
4052                 }
4053
4054                 let per_peer_state = self.per_peer_state.write().unwrap();
4055                 (per_peer_state.len() as u64).write(writer)?;
4056                 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
4057                         peer_pubkey.write(writer)?;
4058                         let peer_state = peer_state_mutex.lock().unwrap();
4059                         peer_state.latest_features.write(writer)?;
4060                 }
4061
4062                 let events = self.pending_events.lock().unwrap();
4063                 (events.len() as u64).write(writer)?;
4064                 for event in events.iter() {
4065                         event.write(writer)?;
4066                 }
4067
4068                 let background_events = self.pending_background_events.lock().unwrap();
4069                 (background_events.len() as u64).write(writer)?;
4070                 for event in background_events.iter() {
4071                         match event {
4072                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
4073                                         0u8.write(writer)?;
4074                                         funding_txo.write(writer)?;
4075                                         monitor_update.write(writer)?;
4076                                 },
4077                         }
4078                 }
4079
4080                 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
4081
4082                 Ok(())
4083         }
4084 }
4085
4086 /// Arguments for the creation of a ChannelManager that are not deserialized.
4087 ///
4088 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
4089 /// is:
4090 /// 1) Deserialize all stored ChannelMonitors.
4091 /// 2) Deserialize the ChannelManager by filling in this struct and calling:
4092 ///    <(BlockHash, ChannelManager)>::read(reader, args)
4093 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
4094 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
4095 /// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same
4096 ///    way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and
4097 ///    ChannelMonitor::get_funding_txo().
4098 /// 4) Reconnect blocks on your ChannelMonitors.
4099 /// 5) Disconnect/connect blocks on the ChannelManager.
4100 /// 6) Move the ChannelMonitors into your local chain::Watch.
4101 ///
4102 /// Note that the ordering of #4-6 is not of importance, however all three must occur before you
4103 /// call any other methods on the newly-deserialized ChannelManager.
4104 ///
4105 /// Note that because some channels may be closed during deserialization, it is critical that you
4106 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
4107 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
4108 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
4109 /// not force-close the same channels but consider them live), you may end up revoking a state for
4110 /// which you've already broadcasted the transaction.
4111 pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4112         where M::Target: chain::Watch<Signer>,
4113         T::Target: BroadcasterInterface,
4114         K::Target: KeysInterface<Signer = Signer>,
4115         F::Target: FeeEstimator,
4116         L::Target: Logger,
4117 {
4118         /// The keys provider which will give us relevant keys. Some keys will be loaded during
4119         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
4120         /// signing data.
4121         pub keys_manager: K,
4122
4123         /// The fee_estimator for use in the ChannelManager in the future.
4124         ///
4125         /// No calls to the FeeEstimator will be made during deserialization.
4126         pub fee_estimator: F,
4127         /// The chain::Watch for use in the ChannelManager in the future.
4128         ///
4129         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
4130         /// you have deserialized ChannelMonitors separately and will add them to your
4131         /// chain::Watch after deserializing this ChannelManager.
4132         pub chain_monitor: M,
4133
4134         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
4135         /// used to broadcast the latest local commitment transactions of channels which must be
4136         /// force-closed during deserialization.
4137         pub tx_broadcaster: T,
4138         /// The Logger for use in the ChannelManager and which may be used to log information during
4139         /// deserialization.
4140         pub logger: L,
4141         /// Default settings used for new channels. Any existing channels will continue to use the
4142         /// runtime settings which were stored when the ChannelManager was serialized.
4143         pub default_config: UserConfig,
4144
4145         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
4146         /// value.get_funding_txo() should be the key).
4147         ///
4148         /// If a monitor is inconsistent with the channel state during deserialization the channel will
4149         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
4150         /// is true for missing channels as well. If there is a monitor missing for which we find
4151         /// channel data Err(DecodeError::InvalidValue) will be returned.
4152         ///
4153         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
4154         /// this struct.
4155         ///
4156         /// (C-not exported) because we have no HashMap bindings
4157         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
4158 }
4159
4160 impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4161                 ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
4162         where M::Target: chain::Watch<Signer>,
4163                 T::Target: BroadcasterInterface,
4164                 K::Target: KeysInterface<Signer = Signer>,
4165                 F::Target: FeeEstimator,
4166                 L::Target: Logger,
4167         {
4168         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
4169         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
4170         /// populate a HashMap directly from C.
4171         pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
4172                         mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
4173                 Self {
4174                         keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
4175                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
4176                 }
4177         }
4178 }
4179
4180 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
4181 // SipmleArcChannelManager type:
4182 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4183         ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
4184         where M::Target: chain::Watch<Signer>,
4185         T::Target: BroadcasterInterface,
4186         K::Target: KeysInterface<Signer = Signer>,
4187         F::Target: FeeEstimator,
4188         L::Target: Logger,
4189 {
4190         fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4191                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
4192                 Ok((blockhash, Arc::new(chan_manager)))
4193         }
4194 }
4195
4196 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4197         ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
4198         where M::Target: chain::Watch<Signer>,
4199         T::Target: BroadcasterInterface,
4200         K::Target: KeysInterface<Signer = Signer>,
4201         F::Target: FeeEstimator,
4202         L::Target: Logger,
4203 {
4204         fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4205                 let _ver: u8 = Readable::read(reader)?;
4206                 let min_ver: u8 = Readable::read(reader)?;
4207                 if min_ver > SERIALIZATION_VERSION {
4208                         return Err(DecodeError::UnknownVersion);
4209                 }
4210
4211                 let genesis_hash: BlockHash = Readable::read(reader)?;
4212                 let latest_block_height: u32 = Readable::read(reader)?;
4213                 let last_block_hash: BlockHash = Readable::read(reader)?;
4214
4215                 let mut failed_htlcs = Vec::new();
4216
4217                 let channel_count: u64 = Readable::read(reader)?;
4218                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
4219                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4220                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4221                 for _ in 0..channel_count {
4222                         let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
4223                         let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
4224                         funding_txo_set.insert(funding_txo.clone());
4225                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
4226                                 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
4227                                                 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
4228                                                 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
4229                                                 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
4230                                         // If the channel is ahead of the monitor, return InvalidValue:
4231                                         return Err(DecodeError::InvalidValue);
4232                                 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
4233                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
4234                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
4235                                                 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
4236                                         // But if the channel is behind of the monitor, close the channel:
4237                                         let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
4238                                         failed_htlcs.append(&mut new_failed_htlcs);
4239                                         monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4240                                 } else {
4241                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
4242                                                 short_to_id.insert(short_channel_id, channel.channel_id());
4243                                         }
4244                                         by_id.insert(channel.channel_id(), channel);
4245                                 }
4246                         } else {
4247                                 return Err(DecodeError::InvalidValue);
4248                         }
4249                 }
4250
4251                 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
4252                         if !funding_txo_set.contains(funding_txo) {
4253                                 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4254                         }
4255                 }
4256
4257                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
4258                 let forward_htlcs_count: u64 = Readable::read(reader)?;
4259                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
4260                 for _ in 0..forward_htlcs_count {
4261                         let short_channel_id = Readable::read(reader)?;
4262                         let pending_forwards_count: u64 = Readable::read(reader)?;
4263                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
4264                         for _ in 0..pending_forwards_count {
4265                                 pending_forwards.push(Readable::read(reader)?);
4266                         }
4267                         forward_htlcs.insert(short_channel_id, pending_forwards);
4268                 }
4269
4270                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
4271                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
4272                 for _ in 0..claimable_htlcs_count {
4273                         let payment_hash = Readable::read(reader)?;
4274                         let previous_hops_len: u64 = Readable::read(reader)?;
4275                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
4276                         for _ in 0..previous_hops_len {
4277                                 previous_hops.push(Readable::read(reader)?);
4278                         }
4279                         claimable_htlcs.insert(payment_hash, previous_hops);
4280                 }
4281
4282                 let peer_count: u64 = Readable::read(reader)?;
4283                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
4284                 for _ in 0..peer_count {
4285                         let peer_pubkey = Readable::read(reader)?;
4286                         let peer_state = PeerState {
4287                                 latest_features: Readable::read(reader)?,
4288                         };
4289                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
4290                 }
4291
4292                 let event_count: u64 = Readable::read(reader)?;
4293                 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>()));
4294                 for _ in 0..event_count {
4295                         match MaybeReadable::read(reader)? {
4296                                 Some(event) => pending_events_read.push(event),
4297                                 None => continue,
4298                         }
4299                 }
4300
4301                 let background_event_count: u64 = Readable::read(reader)?;
4302                 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>()));
4303                 for _ in 0..background_event_count {
4304                         match <u8 as Readable>::read(reader)? {
4305                                 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
4306                                 _ => return Err(DecodeError::InvalidValue),
4307                         }
4308                 }
4309
4310                 let last_node_announcement_serial: u32 = Readable::read(reader)?;
4311
4312                 let mut secp_ctx = Secp256k1::new();
4313                 secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
4314
4315                 let channel_manager = ChannelManager {
4316                         genesis_hash,
4317                         fee_estimator: args.fee_estimator,
4318                         chain_monitor: args.chain_monitor,
4319                         tx_broadcaster: args.tx_broadcaster,
4320
4321                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
4322                         last_block_hash: RwLock::new(last_block_hash),
4323
4324                         channel_state: Mutex::new(ChannelHolder {
4325                                 by_id,
4326                                 short_to_id,
4327                                 forward_htlcs,
4328                                 claimable_htlcs,
4329                                 pending_msg_events: Vec::new(),
4330                         }),
4331                         our_network_key: args.keys_manager.get_node_secret(),
4332                         our_network_pubkey: PublicKey::from_secret_key(&secp_ctx, &args.keys_manager.get_node_secret()),
4333                         secp_ctx,
4334
4335                         last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
4336
4337                         per_peer_state: RwLock::new(per_peer_state),
4338
4339                         pending_events: Mutex::new(pending_events_read),
4340                         pending_background_events: Mutex::new(pending_background_events_read),
4341                         total_consistency_lock: RwLock::new(()),
4342                         persistence_notifier: PersistenceNotifier::new(),
4343
4344                         keys_manager: args.keys_manager,
4345                         logger: args.logger,
4346                         default_configuration: args.default_config,
4347                 };
4348
4349                 for htlc_source in failed_htlcs.drain(..) {
4350                         channel_manager.fail_htlc_backwards_internal(channel_manager.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
4351                 }
4352
4353                 //TODO: Broadcast channel update for closed channels, but only after we've made a
4354                 //connection or two.
4355
4356                 Ok((last_block_hash.clone(), channel_manager))
4357         }
4358 }
4359
4360 #[cfg(test)]
4361 mod tests {
4362         use ln::channelmanager::PersistenceNotifier;
4363         use std::sync::Arc;
4364         use std::sync::atomic::{AtomicBool, Ordering};
4365         use std::thread;
4366         use std::time::Duration;
4367
4368         #[test]
4369         fn test_wait_timeout() {
4370                 let persistence_notifier = Arc::new(PersistenceNotifier::new());
4371                 let thread_notifier = Arc::clone(&persistence_notifier);
4372
4373                 let exit_thread = Arc::new(AtomicBool::new(false));
4374                 let exit_thread_clone = exit_thread.clone();
4375                 thread::spawn(move || {
4376                         loop {
4377                                 let &(ref persist_mtx, ref cnd) = &thread_notifier.persistence_lock;
4378                                 let mut persistence_lock = persist_mtx.lock().unwrap();
4379                                 *persistence_lock = true;
4380                                 cnd.notify_all();
4381
4382                                 if exit_thread_clone.load(Ordering::SeqCst) {
4383                                         break
4384                                 }
4385                         }
4386                 });
4387
4388                 // Check that we can block indefinitely until updates are available.
4389                 let _ = persistence_notifier.wait();
4390
4391                 // Check that the PersistenceNotifier will return after the given duration if updates are
4392                 // available.
4393                 loop {
4394                         if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4395                                 break
4396                         }
4397                 }
4398
4399                 exit_thread.store(true, Ordering::SeqCst);
4400
4401                 // Check that the PersistenceNotifier will return after the given duration even if no updates
4402                 // are available.
4403                 loop {
4404                         if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4405                                 break
4406                         }
4407                 }
4408         }
4409 }
4410
4411 #[cfg(all(test, feature = "unstable"))]
4412 mod benches {
4413         use chain::Listen;
4414         use chain::chainmonitor::ChainMonitor;
4415         use chain::keysinterface::{KeysManager, InMemorySigner};
4416         use chain::transaction::OutPoint;
4417         use ln::channelmanager::{ChainParameters, ChannelManager, PaymentHash, PaymentPreimage};
4418         use ln::features::InitFeatures;
4419         use ln::functional_test_utils::*;
4420         use ln::msgs::ChannelMessageHandler;
4421         use routing::network_graph::NetworkGraph;
4422         use routing::router::get_route;
4423         use util::test_utils;
4424         use util::config::UserConfig;
4425         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
4426
4427         use bitcoin::hashes::Hash;
4428         use bitcoin::hashes::sha256::Hash as Sha256;
4429         use bitcoin::{Block, BlockHeader, Transaction, TxOut};
4430
4431         use std::sync::Mutex;
4432
4433         use test::Bencher;
4434
4435         struct NodeHolder<'a> {
4436                 node: &'a ChannelManager<InMemorySigner,
4437                         &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
4438                                 &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
4439                                 &'a test_utils::TestLogger, &'a test_utils::TestPersister>,
4440                         &'a test_utils::TestBroadcaster, &'a KeysManager,
4441                         &'a test_utils::TestFeeEstimator, &'a test_utils::TestLogger>
4442         }
4443
4444         #[bench]
4445         fn bench_sends(bench: &mut Bencher) {
4446                 // Do a simple benchmark of sending a payment back and forth between two nodes.
4447                 // Note that this is unrealistic as each payment send will require at least two fsync
4448                 // calls per node.
4449                 let network = bitcoin::Network::Testnet;
4450                 let genesis_hash = bitcoin::blockdata::constants::genesis_block(network).header.block_hash();
4451
4452                 let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
4453                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4454
4455                 let mut config: UserConfig = Default::default();
4456                 config.own_channel_config.minimum_depth = 1;
4457
4458                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
4459                 let persister_a = test_utils::TestPersister::new();
4460                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
4461                 let seed_a = [1u8; 32];
4462                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
4463                 let node_a = ChannelManager::new(&fee_estimator, &chain_monitor_a, &tx_broadcaster, &logger_a, &keys_manager_a, config.clone(), ChainParameters {
4464                         network,
4465                         latest_hash: genesis_hash,
4466                         latest_height: 0,
4467                 });
4468                 let node_a_holder = NodeHolder { node: &node_a };
4469
4470                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
4471                 let persister_b = test_utils::TestPersister::new();
4472                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
4473                 let seed_b = [2u8; 32];
4474                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
4475                 let node_b = ChannelManager::new(&fee_estimator, &chain_monitor_b, &tx_broadcaster, &logger_b, &keys_manager_b, config.clone(), ChainParameters {
4476                         network,
4477                         latest_hash: genesis_hash,
4478                         latest_height: 0,
4479                 });
4480                 let node_b_holder = NodeHolder { node: &node_b };
4481
4482                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
4483                 node_b.handle_open_channel(&node_a.get_our_node_id(), InitFeatures::known(), &get_event_msg!(node_a_holder, MessageSendEvent::SendOpenChannel, node_b.get_our_node_id()));
4484                 node_a.handle_accept_channel(&node_b.get_our_node_id(), InitFeatures::known(), &get_event_msg!(node_b_holder, MessageSendEvent::SendAcceptChannel, node_a.get_our_node_id()));
4485
4486                 let tx;
4487                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
4488                         tx = Transaction { version: 2, lock_time: 0, input: Vec::new(), output: vec![TxOut {
4489                                 value: 8_000_000, script_pubkey: output_script,
4490                         }]};
4491                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
4492                         node_a.funding_transaction_generated(&temporary_channel_id, funding_outpoint);
4493                 } else { panic!(); }
4494
4495                 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()));
4496                 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()));
4497
4498                 get_event!(node_a_holder, Event::FundingBroadcastSafe);
4499
4500                 let block = Block {
4501                         header: BlockHeader { version: 0x20000000, prev_blockhash: genesis_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4502                         txdata: vec![tx],
4503                 };
4504                 Listen::block_connected(&node_a, &block, 1);
4505                 Listen::block_connected(&node_b, &block, 1);
4506
4507                 node_a.handle_funding_locked(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendFundingLocked, node_a.get_our_node_id()));
4508                 node_b.handle_funding_locked(&node_a.get_our_node_id(), &get_event_msg!(node_a_holder, MessageSendEvent::SendFundingLocked, node_b.get_our_node_id()));
4509
4510                 let dummy_graph = NetworkGraph::new(genesis_hash);
4511
4512                 macro_rules! send_payment {
4513                         ($node_a: expr, $node_b: expr) => {
4514                                 let usable_channels = $node_a.list_usable_channels();
4515                                 let route = get_route(&$node_a.get_our_node_id(), &dummy_graph, &$node_b.get_our_node_id(), None, Some(&usable_channels.iter().map(|r| r).collect::<Vec<_>>()), &[], 10_000, TEST_FINAL_CLTV, &logger_a).unwrap();
4516
4517                                 let payment_preimage = PaymentPreimage([0; 32]);
4518                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
4519
4520                                 $node_a.send_payment(&route, payment_hash, &None).unwrap();
4521                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
4522                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
4523                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
4524                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_b }, $node_a.get_our_node_id());
4525                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
4526                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
4527                                 $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()));
4528
4529                                 expect_pending_htlcs_forwardable!(NodeHolder { node: &$node_b });
4530                                 expect_payment_received!(NodeHolder { node: &$node_b }, payment_hash, 10_000);
4531                                 assert!($node_b.claim_funds(payment_preimage, &None, 10_000));
4532
4533                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
4534                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
4535                                                 assert_eq!(node_id, $node_a.get_our_node_id());
4536                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4537                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
4538                                         },
4539                                         _ => panic!("Failed to generate claim event"),
4540                                 }
4541
4542                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_a }, $node_b.get_our_node_id());
4543                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
4544                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
4545                                 $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()));
4546
4547                                 expect_payment_sent!(NodeHolder { node: &$node_a }, payment_preimage);
4548                         }
4549                 }
4550
4551                 bench.iter(|| {
4552                         send_payment!(node_a, node_b);
4553                         send_payment!(node_b, node_a);
4554                 });
4555         }
4556 }