Merge pull request #838 from TheBlueMatt/2021-03-skip-blocks
[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<PublicKey, 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                                                 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1015                                         }
1016                                 }
1017                                 if let Some(short_id) = chan.get().get_short_channel_id() {
1018                                         channel_state.short_to_id.remove(&short_id);
1019                                 }
1020                                 chan.remove_entry().1
1021                         } else {
1022                                 return Err(APIError::ChannelUnavailable{err: "No such channel".to_owned()});
1023                         }
1024                 };
1025                 log_trace!(self.logger, "Force-closing channel {}", log_bytes!(channel_id[..]));
1026                 self.finish_force_close_channel(chan.force_shutdown(true));
1027                 if let Ok(update) = self.get_channel_update(&chan) {
1028                         let mut channel_state = self.channel_state.lock().unwrap();
1029                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1030                                 msg: update
1031                         });
1032                 }
1033
1034                 Ok(chan.get_counterparty_node_id())
1035         }
1036
1037         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
1038         /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
1039         pub fn force_close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
1040                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1041                 match self.force_close_channel_with_peer(channel_id, None) {
1042                         Ok(counterparty_node_id) => {
1043                                 self.channel_state.lock().unwrap().pending_msg_events.push(
1044                                         events::MessageSendEvent::HandleError {
1045                                                 node_id: counterparty_node_id,
1046                                                 action: msgs::ErrorAction::SendErrorMessage {
1047                                                         msg: msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() }
1048                                                 },
1049                                         }
1050                                 );
1051                                 Ok(())
1052                         },
1053                         Err(e) => Err(e)
1054                 }
1055         }
1056
1057         /// Force close all channels, immediately broadcasting the latest local commitment transaction
1058         /// for each to the chain and rejecting new HTLCs on each.
1059         pub fn force_close_all_channels(&self) {
1060                 for chan in self.list_channels() {
1061                         let _ = self.force_close_channel(&chan.channel_id);
1062                 }
1063         }
1064
1065         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder<Signer>>) {
1066                 macro_rules! return_malformed_err {
1067                         ($msg: expr, $err_code: expr) => {
1068                                 {
1069                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1070                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
1071                                                 channel_id: msg.channel_id,
1072                                                 htlc_id: msg.htlc_id,
1073                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
1074                                                 failure_code: $err_code,
1075                                         })), self.channel_state.lock().unwrap());
1076                                 }
1077                         }
1078                 }
1079
1080                 if let Err(_) = msg.onion_routing_packet.public_key {
1081                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
1082                 }
1083
1084                 let shared_secret = {
1085                         let mut arr = [0; 32];
1086                         arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1087                         arr
1088                 };
1089                 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
1090
1091                 if msg.onion_routing_packet.version != 0 {
1092                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1093                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1094                         //the hash doesn't really serve any purpose - in the case of hashing all data, the
1095                         //receiving node would have to brute force to figure out which version was put in the
1096                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1097                         //node knows the HMAC matched, so they already know what is there...
1098                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1099                 }
1100
1101                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
1102                 hmac.input(&msg.onion_routing_packet.hop_data);
1103                 hmac.input(&msg.payment_hash.0[..]);
1104                 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
1105                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
1106                 }
1107
1108                 let mut channel_state = None;
1109                 macro_rules! return_err {
1110                         ($msg: expr, $err_code: expr, $data: expr) => {
1111                                 {
1112                                         log_info!(self.logger, "Failed to accept/forward incoming HTLC: {}", $msg);
1113                                         if channel_state.is_none() {
1114                                                 channel_state = Some(self.channel_state.lock().unwrap());
1115                                         }
1116                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1117                                                 channel_id: msg.channel_id,
1118                                                 htlc_id: msg.htlc_id,
1119                                                 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1120                                         })), channel_state.unwrap());
1121                                 }
1122                         }
1123                 }
1124
1125                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1126                 let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&msg.onion_routing_packet.hop_data[..]) };
1127                 let (next_hop_data, next_hop_hmac) = {
1128                         match msgs::OnionHopData::read(&mut chacha_stream) {
1129                                 Err(err) => {
1130                                         let error_code = match err {
1131                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1132                                                 msgs::DecodeError::UnknownRequiredFeature|
1133                                                 msgs::DecodeError::InvalidValue|
1134                                                 msgs::DecodeError::ShortRead => 0x4000 | 22, // invalid_onion_payload
1135                                                 _ => 0x2000 | 2, // Should never happen
1136                                         };
1137                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1138                                 },
1139                                 Ok(msg) => {
1140                                         let mut hmac = [0; 32];
1141                                         if let Err(_) = chacha_stream.read_exact(&mut hmac[..]) {
1142                                                 return_err!("Unable to decode hop data", 0x4000 | 22, &[0;0]);
1143                                         }
1144                                         (msg, hmac)
1145                                 },
1146                         }
1147                 };
1148
1149                 let pending_forward_info = if next_hop_hmac == [0; 32] {
1150                                 #[cfg(test)]
1151                                 {
1152                                         // In tests, make sure that the initial onion pcket data is, at least, non-0.
1153                                         // We could do some fancy randomness test here, but, ehh, whatever.
1154                                         // This checks for the issue where you can calculate the path length given the
1155                                         // onion data as all the path entries that the originator sent will be here
1156                                         // as-is (and were originally 0s).
1157                                         // Of course reverse path calculation is still pretty easy given naive routing
1158                                         // algorithms, but this fixes the most-obvious case.
1159                                         let mut next_bytes = [0; 32];
1160                                         chacha_stream.read_exact(&mut next_bytes).unwrap();
1161                                         assert_ne!(next_bytes[..], [0; 32][..]);
1162                                         chacha_stream.read_exact(&mut next_bytes).unwrap();
1163                                         assert_ne!(next_bytes[..], [0; 32][..]);
1164                                 }
1165
1166                                 // OUR PAYMENT!
1167                                 // final_expiry_too_soon
1168                                 // We have to have some headroom to broadcast on chain if we have the preimage, so make sure we have at least
1169                                 // HTLC_FAIL_BACK_BUFFER blocks to go.
1170                                 // Also, ensure that, in the case of an unknown payment hash, our payment logic has enough time to fail the HTLC backward
1171                                 // before our onchain logic triggers a channel closure (see HTLC_FAIL_BACK_BUFFER rational).
1172                                 if (msg.cltv_expiry as u64) <= self.latest_block_height.load(Ordering::Acquire) as u64 + HTLC_FAIL_BACK_BUFFER as u64 + 1 {
1173                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1174                                 }
1175                                 // final_incorrect_htlc_amount
1176                                 if next_hop_data.amt_to_forward > msg.amount_msat {
1177                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1178                                 }
1179                                 // final_incorrect_cltv_expiry
1180                                 if next_hop_data.outgoing_cltv_value != msg.cltv_expiry {
1181                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1182                                 }
1183
1184                                 let payment_data = match next_hop_data.format {
1185                                         msgs::OnionHopDataFormat::Legacy { .. } => None,
1186                                         msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1187                                         msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1188                                 };
1189
1190                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1191                                 // message, however that would leak that we are the recipient of this payment, so
1192                                 // instead we stay symmetric with the forwarding case, only responding (after a
1193                                 // delay) once they've send us a commitment_signed!
1194
1195                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
1196                                         routing: PendingHTLCRouting::Receive {
1197                                                 payment_data,
1198                                                 incoming_cltv_expiry: msg.cltv_expiry,
1199                                         },
1200                                         payment_hash: msg.payment_hash.clone(),
1201                                         incoming_shared_secret: shared_secret,
1202                                         amt_to_forward: next_hop_data.amt_to_forward,
1203                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1204                                 })
1205                         } else {
1206                                 let mut new_packet_data = [0; 20*65];
1207                                 let read_pos = chacha_stream.read(&mut new_packet_data).unwrap();
1208                                 #[cfg(debug_assertions)]
1209                                 {
1210                                         // Check two things:
1211                                         // a) that the behavior of our stream here will return Ok(0) even if the TLV
1212                                         //    read above emptied out our buffer and the unwrap() wont needlessly panic
1213                                         // b) that we didn't somehow magically end up with extra data.
1214                                         let mut t = [0; 1];
1215                                         debug_assert!(chacha_stream.read(&mut t).unwrap() == 0);
1216                                 }
1217                                 // Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
1218                                 // fill the onion hop data we'll forward to our next-hop peer.
1219                                 chacha_stream.chacha.process_in_place(&mut new_packet_data[read_pos..]);
1220
1221                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1222
1223                                 let blinding_factor = {
1224                                         let mut sha = Sha256::engine();
1225                                         sha.input(&new_pubkey.serialize()[..]);
1226                                         sha.input(&shared_secret);
1227                                         Sha256::from_engine(sha).into_inner()
1228                                 };
1229
1230                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
1231                                         Err(e)
1232                                 } else { Ok(new_pubkey) };
1233
1234                                 let outgoing_packet = msgs::OnionPacket {
1235                                         version: 0,
1236                                         public_key,
1237                                         hop_data: new_packet_data,
1238                                         hmac: next_hop_hmac.clone(),
1239                                 };
1240
1241                                 let short_channel_id = match next_hop_data.format {
1242                                         msgs::OnionHopDataFormat::Legacy { short_channel_id } => short_channel_id,
1243                                         msgs::OnionHopDataFormat::NonFinalNode { short_channel_id } => short_channel_id,
1244                                         msgs::OnionHopDataFormat::FinalNode { .. } => {
1245                                                 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0;0]);
1246                                         },
1247                                 };
1248
1249                                 PendingHTLCStatus::Forward(PendingHTLCInfo {
1250                                         routing: PendingHTLCRouting::Forward {
1251                                                 onion_packet: outgoing_packet,
1252                                                 short_channel_id,
1253                                         },
1254                                         payment_hash: msg.payment_hash.clone(),
1255                                         incoming_shared_secret: shared_secret,
1256                                         amt_to_forward: next_hop_data.amt_to_forward,
1257                                         outgoing_cltv_value: next_hop_data.outgoing_cltv_value,
1258                                 })
1259                         };
1260
1261                 channel_state = Some(self.channel_state.lock().unwrap());
1262                 if let &PendingHTLCStatus::Forward(PendingHTLCInfo { ref routing, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1263                         // If short_channel_id is 0 here, we'll reject the HTLC as there cannot be a channel
1264                         // with a short_channel_id of 0. This is important as various things later assume
1265                         // short_channel_id is non-0 in any ::Forward.
1266                         if let &PendingHTLCRouting::Forward { ref short_channel_id, .. } = routing {
1267                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1268                                 let forwarding_id = match id_option {
1269                                         None => { // unknown_next_peer
1270                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1271                                         },
1272                                         Some(id) => id.clone(),
1273                                 };
1274                                 if let Some((err, code, chan_update)) = loop {
1275                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1276
1277                                         // Note that we could technically not return an error yet here and just hope
1278                                         // that the connection is reestablished or monitor updated by the time we get
1279                                         // around to doing the actual forward, but better to fail early if we can and
1280                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1281                                         // on a small/per-node/per-channel scale.
1282                                         if !chan.is_live() { // channel_disabled
1283                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1284                                         }
1285                                         if *amt_to_forward < chan.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
1286                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1287                                         }
1288                                         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) });
1289                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1290                                                 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())));
1291                                         }
1292                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + chan.get_cltv_expiry_delta() as u64 { // incorrect_cltv_expiry
1293                                                 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())));
1294                                         }
1295                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1296                                         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now, but we want to be robust wrt to counterparty
1297                                         // packet sanitization (see HTLC_FAIL_BACK_BUFFER rational)
1298                                         if msg.cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
1299                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1300                                         }
1301                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1302                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1303                                         }
1304                                         // In theory, we would be safe against unitentional channel-closure, if we only required a margin of LATENCY_GRACE_PERIOD_BLOCKS.
1305                                         // But, to be safe against policy reception, we use a longuer delay.
1306                                         if (*outgoing_cltv_value) as u64 <= (cur_height + HTLC_FAIL_BACK_BUFFER) as u64 {
1307                                                 break Some(("Outgoing CLTV value is too soon", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1308                                         }
1309
1310                                         break None;
1311                                 }
1312                                 {
1313                                         let mut res = Vec::with_capacity(8 + 128);
1314                                         if let Some(chan_update) = chan_update {
1315                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1316                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1317                                                 }
1318                                                 else if code == 0x1000 | 13 {
1319                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1320                                                 }
1321                                                 else if code == 0x1000 | 20 {
1322                                                         // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
1323                                                         res.extend_from_slice(&byte_utils::be16_to_array(0));
1324                                                 }
1325                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1326                                         }
1327                                         return_err!(err, code, &res[..]);
1328                                 }
1329                         }
1330                 }
1331
1332                 (pending_forward_info, channel_state.unwrap())
1333         }
1334
1335         /// only fails if the channel does not yet have an assigned short_id
1336         /// May be called with channel_state already locked!
1337         fn get_channel_update(&self, chan: &Channel<Signer>) -> Result<msgs::ChannelUpdate, LightningError> {
1338                 let short_channel_id = match chan.get_short_channel_id() {
1339                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
1340                         Some(id) => id,
1341                 };
1342
1343                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_counterparty_node_id().serialize()[..];
1344
1345                 let unsigned = msgs::UnsignedChannelUpdate {
1346                         chain_hash: self.genesis_hash,
1347                         short_channel_id,
1348                         timestamp: chan.get_update_time_counter(),
1349                         flags: (!were_node_one) as u8 | ((!chan.is_live() as u8) << 1),
1350                         cltv_expiry_delta: chan.get_cltv_expiry_delta(),
1351                         htlc_minimum_msat: chan.get_counterparty_htlc_minimum_msat(),
1352                         htlc_maximum_msat: OptionalField::Present(chan.get_announced_htlc_max_msat()),
1353                         fee_base_msat: chan.get_holder_fee_base_msat(&self.fee_estimator),
1354                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1355                         excess_data: Vec::new(),
1356                 };
1357
1358                 let msg_hash = Sha256dHash::hash(&unsigned.encode()[..]);
1359                 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
1360
1361                 Ok(msgs::ChannelUpdate {
1362                         signature: sig,
1363                         contents: unsigned
1364                 })
1365         }
1366
1367         // Only public for testing, this should otherwise never be called direcly
1368         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> {
1369                 log_trace!(self.logger, "Attempting to send payment for path with next hop {}", path.first().unwrap().short_channel_id);
1370                 let prng_seed = self.keys_manager.get_secure_random_bytes();
1371                 let session_priv = SecretKey::from_slice(&self.keys_manager.get_secure_random_bytes()[..]).expect("RNG is busted");
1372
1373                 let onion_keys = onion_utils::construct_onion_keys(&self.secp_ctx, &path, &session_priv)
1374                         .map_err(|_| APIError::RouteError{err: "Pubkey along hop was maliciously selected"})?;
1375                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(path, total_value, payment_secret, cur_height)?;
1376                 if onion_utils::route_size_insane(&onion_payloads) {
1377                         return Err(APIError::RouteError{err: "Route size too large considering onion data"});
1378                 }
1379                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, prng_seed, payment_hash);
1380
1381                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1382
1383                 let err: Result<(), _> = loop {
1384                         let mut channel_lock = self.channel_state.lock().unwrap();
1385                         let id = match channel_lock.short_to_id.get(&path.first().unwrap().short_channel_id) {
1386                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()}),
1387                                 Some(id) => id.clone(),
1388                         };
1389
1390                         let channel_state = &mut *channel_lock;
1391                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1392                                 match {
1393                                         if chan.get().get_counterparty_node_id() != path.first().unwrap().pubkey {
1394                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1395                                         }
1396                                         if !chan.get().is_live() {
1397                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!".to_owned()});
1398                                         }
1399                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1400                                                 path: path.clone(),
1401                                                 session_priv: session_priv.clone(),
1402                                                 first_hop_htlc_msat: htlc_msat,
1403                                         }, onion_packet, &self.logger), channel_state, chan)
1404                                 } {
1405                                         Some((update_add, commitment_signed, monitor_update)) => {
1406                                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1407                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1408                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1409                                                         // that we will resend the commitment update once monitor updating
1410                                                         // is restored. Therefore, we must return an error indicating that
1411                                                         // it is unsafe to retry the payment wholesale, which we do in the
1412                                                         // send_payment check for MonitorUpdateFailed, below.
1413                                                         return Err(APIError::MonitorUpdateFailed);
1414                                                 }
1415
1416                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1417                                                         node_id: path.first().unwrap().pubkey,
1418                                                         updates: msgs::CommitmentUpdate {
1419                                                                 update_add_htlcs: vec![update_add],
1420                                                                 update_fulfill_htlcs: Vec::new(),
1421                                                                 update_fail_htlcs: Vec::new(),
1422                                                                 update_fail_malformed_htlcs: Vec::new(),
1423                                                                 update_fee: None,
1424                                                                 commitment_signed,
1425                                                         },
1426                                                 });
1427                                         },
1428                                         None => {},
1429                                 }
1430                         } else { unreachable!(); }
1431                         return Ok(());
1432                 };
1433
1434                 match handle_error!(self, err, path.first().unwrap().pubkey) {
1435                         Ok(_) => unreachable!(),
1436                         Err(e) => {
1437                                 Err(APIError::ChannelUnavailable { err: e.err })
1438                         },
1439                 }
1440         }
1441
1442         /// Sends a payment along a given route.
1443         ///
1444         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1445         /// fields for more info.
1446         ///
1447         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1448         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1449         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1450         /// specified in the last hop in the route! Thus, you should probably do your own
1451         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1452         /// payment") and prevent double-sends yourself.
1453         ///
1454         /// May generate SendHTLCs message(s) event on success, which should be relayed.
1455         ///
1456         /// Each path may have a different return value, and PaymentSendValue may return a Vec with
1457         /// each entry matching the corresponding-index entry in the route paths, see
1458         /// PaymentSendFailure for more info.
1459         ///
1460         /// In general, a path may raise:
1461         ///  * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
1462         ///    node public key) is specified.
1463         ///  * APIError::ChannelUnavailable if the next-hop channel is not available for updates
1464         ///    (including due to previous monitor update failure or new permanent monitor update
1465         ///    failure).
1466         ///  * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1467         ///    relevant updates.
1468         ///
1469         /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
1470         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
1471         /// different route unless you intend to pay twice!
1472         ///
1473         /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
1474         /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
1475         /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
1476         /// must not contain multiple paths as multi-path payments require a recipient-provided
1477         /// payment_secret.
1478         /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
1479         /// bit set (either as required or as available). If multiple paths are present in the Route,
1480         /// we assume the invoice had the basic_mpp feature set.
1481         pub fn send_payment(&self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>) -> Result<(), PaymentSendFailure> {
1482                 if route.paths.len() < 1 {
1483                         return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "There must be at least one path to send over"}));
1484                 }
1485                 if route.paths.len() > 10 {
1486                         // This limit is completely arbitrary - there aren't any real fundamental path-count
1487                         // limits. After we support retrying individual paths we should likely bump this, but
1488                         // for now more than 10 paths likely carries too much one-path failure.
1489                         return Err(PaymentSendFailure::ParameterError(APIError::RouteError{err: "Sending over more than 10 paths is not currently supported"}));
1490                 }
1491                 let mut total_value = 0;
1492                 let our_node_id = self.get_our_node_id();
1493                 let mut path_errs = Vec::with_capacity(route.paths.len());
1494                 'path_check: for path in route.paths.iter() {
1495                         if path.len() < 1 || path.len() > 20 {
1496                                 path_errs.push(Err(APIError::RouteError{err: "Path didn't go anywhere/had bogus size"}));
1497                                 continue 'path_check;
1498                         }
1499                         for (idx, hop) in path.iter().enumerate() {
1500                                 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1501                                         path_errs.push(Err(APIError::RouteError{err: "Path went through us but wasn't a simple rebalance loop to us"}));
1502                                         continue 'path_check;
1503                                 }
1504                         }
1505                         total_value += path.last().unwrap().fee_msat;
1506                         path_errs.push(Ok(()));
1507                 }
1508                 if path_errs.iter().any(|e| e.is_err()) {
1509                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1510                 }
1511
1512                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1513                 let mut results = Vec::new();
1514                 for path in route.paths.iter() {
1515                         results.push(self.send_payment_along_path(&path, &payment_hash, payment_secret, total_value, cur_height));
1516                 }
1517                 let mut has_ok = false;
1518                 let mut has_err = false;
1519                 for res in results.iter() {
1520                         if res.is_ok() { has_ok = true; }
1521                         if res.is_err() { has_err = true; }
1522                         if let &Err(APIError::MonitorUpdateFailed) = res {
1523                                 // MonitorUpdateFailed is inherently unsafe to retry, so we call it a
1524                                 // PartialFailure.
1525                                 has_err = true;
1526                                 has_ok = true;
1527                                 break;
1528                         }
1529                 }
1530                 if has_err && has_ok {
1531                         Err(PaymentSendFailure::PartialFailure(results))
1532                 } else if has_err {
1533                         Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1534                 } else {
1535                         Ok(())
1536                 }
1537         }
1538
1539         /// Call this upon creation of a funding transaction for the given channel.
1540         ///
1541         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1542         /// or your counterparty can steal your funds!
1543         ///
1544         /// Panics if a funding transaction has already been provided for this channel.
1545         ///
1546         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1547         /// be trivially prevented by using unique funding transaction keys per-channel).
1548         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1549                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1550
1551                 let (chan, msg) = {
1552                         let (res, chan) = match self.channel_state.lock().unwrap().by_id.remove(temporary_channel_id) {
1553                                 Some(mut chan) => {
1554                                         (chan.get_outbound_funding_created(funding_txo, &self.logger)
1555                                                 .map_err(|e| if let ChannelError::Close(msg) = e {
1556                                                         MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(true), None)
1557                                                 } else { unreachable!(); })
1558                                         , chan)
1559                                 },
1560                                 None => return
1561                         };
1562                         match handle_error!(self, res, chan.get_counterparty_node_id()) {
1563                                 Ok(funding_msg) => {
1564                                         (chan, funding_msg)
1565                                 },
1566                                 Err(_) => { return; }
1567                         }
1568                 };
1569
1570                 let mut channel_state = self.channel_state.lock().unwrap();
1571                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1572                         node_id: chan.get_counterparty_node_id(),
1573                         msg,
1574                 });
1575                 match channel_state.by_id.entry(chan.channel_id()) {
1576                         hash_map::Entry::Occupied(_) => {
1577                                 panic!("Generated duplicate funding txid?");
1578                         },
1579                         hash_map::Entry::Vacant(e) => {
1580                                 e.insert(chan);
1581                         }
1582                 }
1583         }
1584
1585         fn get_announcement_sigs(&self, chan: &Channel<Signer>) -> Option<msgs::AnnouncementSignatures> {
1586                 if !chan.should_announce() {
1587                         log_trace!(self.logger, "Can't send announcement_signatures for private channel {}", log_bytes!(chan.channel_id()));
1588                         return None
1589                 }
1590
1591                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1592                         Ok(res) => res,
1593                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1594                 };
1595                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1596                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1597
1598                 Some(msgs::AnnouncementSignatures {
1599                         channel_id: chan.channel_id(),
1600                         short_channel_id: chan.get_short_channel_id().unwrap(),
1601                         node_signature: our_node_sig,
1602                         bitcoin_signature: our_bitcoin_sig,
1603                 })
1604         }
1605
1606         #[allow(dead_code)]
1607         // Messages of up to 64KB should never end up more than half full with addresses, as that would
1608         // be absurd. We ensure this by checking that at least 500 (our stated public contract on when
1609         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1610         // message...
1611         const HALF_MESSAGE_IS_ADDRS: u32 = ::std::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1612         #[deny(const_err)]
1613         #[allow(dead_code)]
1614         // ...by failing to compile if the number of addresses that would be half of a message is
1615         // smaller than 500:
1616         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 500;
1617
1618         /// Generates a signed node_announcement from the given arguments and creates a
1619         /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
1620         /// seen a channel_announcement from us (ie unless we have public channels open).
1621         ///
1622         /// RGB is a node "color" and alias is a printable human-readable string to describe this node
1623         /// to humans. They carry no in-protocol meaning.
1624         ///
1625         /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
1626         /// incoming connections. These will be broadcast to the network, publicly tying these
1627         /// addresses together. If you wish to preserve user privacy, addresses should likely contain
1628         /// only Tor Onion addresses.
1629         ///
1630         /// Panics if addresses is absurdly large (more than 500).
1631         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], addresses: Vec<NetAddress>) {
1632                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1633
1634                 if addresses.len() > 500 {
1635                         panic!("More than half the message size was taken up by public addresses!");
1636                 }
1637
1638                 let announcement = msgs::UnsignedNodeAnnouncement {
1639                         features: NodeFeatures::known(),
1640                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1641                         node_id: self.get_our_node_id(),
1642                         rgb, alias, addresses,
1643                         excess_address_data: Vec::new(),
1644                         excess_data: Vec::new(),
1645                 };
1646                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1647
1648                 let mut channel_state = self.channel_state.lock().unwrap();
1649                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastNodeAnnouncement {
1650                         msg: msgs::NodeAnnouncement {
1651                                 signature: self.secp_ctx.sign(&msghash, &self.our_network_key),
1652                                 contents: announcement
1653                         },
1654                 });
1655         }
1656
1657         /// Processes HTLCs which are pending waiting on random forward delay.
1658         ///
1659         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
1660         /// Will likely generate further events.
1661         pub fn process_pending_htlc_forwards(&self) {
1662                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1663
1664                 let mut new_events = Vec::new();
1665                 let mut failed_forwards = Vec::new();
1666                 let mut handle_errors = Vec::new();
1667                 {
1668                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1669                         let channel_state = &mut *channel_state_lock;
1670
1671                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1672                                 if short_chan_id != 0 {
1673                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1674                                                 Some(chan_id) => chan_id.clone(),
1675                                                 None => {
1676                                                         failed_forwards.reserve(pending_forwards.len());
1677                                                         for forward_info in pending_forwards.drain(..) {
1678                                                                 match forward_info {
1679                                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info,
1680                                                                                                    prev_funding_outpoint } => {
1681                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1682                                                                                         short_channel_id: prev_short_channel_id,
1683                                                                                         outpoint: prev_funding_outpoint,
1684                                                                                         htlc_id: prev_htlc_id,
1685                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1686                                                                                 });
1687                                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash,
1688                                                                                         HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() }
1689                                                                                 ));
1690                                                                         },
1691                                                                         HTLCForwardInfo::FailHTLC { .. } => {
1692                                                                                 // Channel went away before we could fail it. This implies
1693                                                                                 // the channel is now on chain and our counterparty is
1694                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
1695                                                                                 // problem, not ours.
1696                                                                         }
1697                                                                 }
1698                                                         }
1699                                                         continue;
1700                                                 }
1701                                         };
1702                                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(forward_chan_id) {
1703                                                 let mut add_htlc_msgs = Vec::new();
1704                                                 let mut fail_htlc_msgs = Vec::new();
1705                                                 for forward_info in pending_forwards.drain(..) {
1706                                                         match forward_info {
1707                                                                 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1708                                                                                 routing: PendingHTLCRouting::Forward {
1709                                                                                         onion_packet, ..
1710                                                                                 }, incoming_shared_secret, payment_hash, amt_to_forward, outgoing_cltv_value },
1711                                                                                 prev_funding_outpoint } => {
1712                                                                         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);
1713                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1714                                                                                 short_channel_id: prev_short_channel_id,
1715                                                                                 outpoint: prev_funding_outpoint,
1716                                                                                 htlc_id: prev_htlc_id,
1717                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
1718                                                                         });
1719                                                                         match chan.get_mut().send_htlc(amt_to_forward, payment_hash, outgoing_cltv_value, htlc_source.clone(), onion_packet) {
1720                                                                                 Err(e) => {
1721                                                                                         if let ChannelError::Ignore(msg) = e {
1722                                                                                                 log_trace!(self.logger, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(payment_hash.0), msg);
1723                                                                                         } else {
1724                                                                                                 panic!("Stated return value requirements in send_htlc() were not met");
1725                                                                                         }
1726                                                                                         let chan_update = self.get_channel_update(chan.get()).unwrap();
1727                                                                                         failed_forwards.push((htlc_source, payment_hash,
1728                                                                                                 HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.encode_with_len() }
1729                                                                                         ));
1730                                                                                         continue;
1731                                                                                 },
1732                                                                                 Ok(update_add) => {
1733                                                                                         match update_add {
1734                                                                                                 Some(msg) => { add_htlc_msgs.push(msg); },
1735                                                                                                 None => {
1736                                                                                                         // Nothing to do here...we're waiting on a remote
1737                                                                                                         // revoke_and_ack before we can add anymore HTLCs. The Channel
1738                                                                                                         // will automatically handle building the update_add_htlc and
1739                                                                                                         // commitment_signed messages when we can.
1740                                                                                                         // TODO: Do some kind of timer to set the channel as !is_live()
1741                                                                                                         // as we don't really want others relying on us relaying through
1742                                                                                                         // this channel currently :/.
1743                                                                                                 }
1744                                                                                         }
1745                                                                                 }
1746                                                                         }
1747                                                                 },
1748                                                                 HTLCForwardInfo::AddHTLC { .. } => {
1749                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
1750                                                                 },
1751                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1752                                                                         log_trace!(self.logger, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1753                                                                         match chan.get_mut().get_update_fail_htlc(htlc_id, err_packet) {
1754                                                                                 Err(e) => {
1755                                                                                         if let ChannelError::Ignore(msg) = e {
1756                                                                                                 log_trace!(self.logger, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1757                                                                                         } else {
1758                                                                                                 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1759                                                                                         }
1760                                                                                         // fail-backs are best-effort, we probably already have one
1761                                                                                         // pending, and if not that's OK, if not, the channel is on
1762                                                                                         // the chain and sending the HTLC-Timeout is their problem.
1763                                                                                         continue;
1764                                                                                 },
1765                                                                                 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1766                                                                                 Ok(None) => {
1767                                                                                         // Nothing to do here...we're waiting on a remote
1768                                                                                         // revoke_and_ack before we can update the commitment
1769                                                                                         // transaction. The Channel will automatically handle
1770                                                                                         // building the update_fail_htlc and commitment_signed
1771                                                                                         // messages when we can.
1772                                                                                         // We don't need any kind of timer here as they should fail
1773                                                                                         // the channel onto the chain if they can't get our
1774                                                                                         // update_fail_htlc in time, it's not our problem.
1775                                                                                 }
1776                                                                         }
1777                                                                 },
1778                                                         }
1779                                                 }
1780
1781                                                 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1782                                                         let (commitment_msg, monitor_update) = match chan.get_mut().send_commitment(&self.logger) {
1783                                                                 Ok(res) => res,
1784                                                                 Err(e) => {
1785                                                                         // We surely failed send_commitment due to bad keys, in that case
1786                                                                         // close channel and then send error message to peer.
1787                                                                         let counterparty_node_id = chan.get().get_counterparty_node_id();
1788                                                                         let err: Result<(), _>  = match e {
1789                                                                                 ChannelError::Ignore(_) => {
1790                                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1791                                                                                 },
1792                                                                                 ChannelError::Close(msg) => {
1793                                                                                         log_trace!(self.logger, "Closing channel {} due to Close-required error: {}", log_bytes!(chan.key()[..]), msg);
1794                                                                                         let (channel_id, mut channel) = chan.remove_entry();
1795                                                                                         if let Some(short_id) = channel.get_short_channel_id() {
1796                                                                                                 channel_state.short_to_id.remove(&short_id);
1797                                                                                         }
1798                                                                                         Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, channel.force_shutdown(true), self.get_channel_update(&channel).ok()))
1799                                                                                 },
1800                                                                                 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"); }
1801                                                                         };
1802                                                                         handle_errors.push((counterparty_node_id, err));
1803                                                                         continue;
1804                                                                 }
1805                                                         };
1806                                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
1807                                                                 handle_errors.push((chan.get().get_counterparty_node_id(), handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true)));
1808                                                                 continue;
1809                                                         }
1810                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1811                                                                 node_id: chan.get().get_counterparty_node_id(),
1812                                                                 updates: msgs::CommitmentUpdate {
1813                                                                         update_add_htlcs: add_htlc_msgs,
1814                                                                         update_fulfill_htlcs: Vec::new(),
1815                                                                         update_fail_htlcs: fail_htlc_msgs,
1816                                                                         update_fail_malformed_htlcs: Vec::new(),
1817                                                                         update_fee: None,
1818                                                                         commitment_signed: commitment_msg,
1819                                                                 },
1820                                                         });
1821                                                 }
1822                                         } else {
1823                                                 unreachable!();
1824                                         }
1825                                 } else {
1826                                         for forward_info in pending_forwards.drain(..) {
1827                                                 match forward_info {
1828                                                         HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1829                                                                         routing: PendingHTLCRouting::Receive { payment_data, incoming_cltv_expiry },
1830                                                                         incoming_shared_secret, payment_hash, amt_to_forward, .. },
1831                                                                         prev_funding_outpoint } => {
1832                                                                 let prev_hop = HTLCPreviousHopData {
1833                                                                         short_channel_id: prev_short_channel_id,
1834                                                                         outpoint: prev_funding_outpoint,
1835                                                                         htlc_id: prev_htlc_id,
1836                                                                         incoming_packet_shared_secret: incoming_shared_secret,
1837                                                                 };
1838
1839                                                                 let mut total_value = 0;
1840                                                                 let payment_secret_opt =
1841                                                                         if let &Some(ref data) = &payment_data { Some(data.payment_secret.clone()) } else { None };
1842                                                                 let htlcs = channel_state.claimable_htlcs.entry((payment_hash, payment_secret_opt))
1843                                                                         .or_insert(Vec::new());
1844                                                                 htlcs.push(ClaimableHTLC {
1845                                                                         prev_hop,
1846                                                                         value: amt_to_forward,
1847                                                                         payment_data: payment_data.clone(),
1848                                                                         cltv_expiry: incoming_cltv_expiry,
1849                                                                 });
1850                                                                 if let &Some(ref data) = &payment_data {
1851                                                                         for htlc in htlcs.iter() {
1852                                                                                 total_value += htlc.value;
1853                                                                                 if htlc.payment_data.as_ref().unwrap().total_msat != data.total_msat {
1854                                                                                         total_value = msgs::MAX_VALUE_MSAT;
1855                                                                                 }
1856                                                                                 if total_value >= msgs::MAX_VALUE_MSAT { break; }
1857                                                                         }
1858                                                                         if total_value >= msgs::MAX_VALUE_MSAT || total_value > data.total_msat  {
1859                                                                                 for htlc in htlcs.iter() {
1860                                                                                         let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1861                                                                                         htlc_msat_height_data.extend_from_slice(
1862                                                                                                 &byte_utils::be32_to_array(
1863                                                                                                         self.latest_block_height.load(Ordering::Acquire)
1864                                                                                                                 as u32,
1865                                                                                                 ),
1866                                                                                         );
1867                                                                                         failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
1868                                                                                                         short_channel_id: htlc.prev_hop.short_channel_id,
1869                                                                                                         outpoint: prev_funding_outpoint,
1870                                                                                                         htlc_id: htlc.prev_hop.htlc_id,
1871                                                                                                         incoming_packet_shared_secret: htlc.prev_hop.incoming_packet_shared_secret,
1872                                                                                                 }), payment_hash,
1873                                                                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data }
1874                                                                                         ));
1875                                                                                 }
1876                                                                         } else if total_value == data.total_msat {
1877                                                                                 new_events.push(events::Event::PaymentReceived {
1878                                                                                         payment_hash,
1879                                                                                         payment_secret: Some(data.payment_secret),
1880                                                                                         amt: total_value,
1881                                                                                 });
1882                                                                         }
1883                                                                 } else {
1884                                                                         new_events.push(events::Event::PaymentReceived {
1885                                                                                 payment_hash,
1886                                                                                 payment_secret: None,
1887                                                                                 amt: amt_to_forward,
1888                                                                         });
1889                                                                 }
1890                                                         },
1891                                                         HTLCForwardInfo::AddHTLC { .. } => {
1892                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
1893                                                         },
1894                                                         HTLCForwardInfo::FailHTLC { .. } => {
1895                                                                 panic!("Got pending fail of our own HTLC");
1896                                                         }
1897                                                 }
1898                                         }
1899                                 }
1900                         }
1901                 }
1902
1903                 for (htlc_source, payment_hash, failure_reason) in failed_forwards.drain(..) {
1904                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, failure_reason);
1905                 }
1906
1907                 for (counterparty_node_id, err) in handle_errors.drain(..) {
1908                         let _ = handle_error!(self, err, counterparty_node_id);
1909                 }
1910
1911                 if new_events.is_empty() { return }
1912                 let mut events = self.pending_events.lock().unwrap();
1913                 events.append(&mut new_events);
1914         }
1915
1916         /// Free the background events, generally called from timer_chan_freshness_every_min.
1917         ///
1918         /// Exposed for testing to allow us to process events quickly without generating accidental
1919         /// BroadcastChannelUpdate events in timer_chan_freshness_every_min.
1920         ///
1921         /// Expects the caller to have a total_consistency_lock read lock.
1922         fn process_background_events(&self) {
1923                 let mut background_events = Vec::new();
1924                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
1925                 for event in background_events.drain(..) {
1926                         match event {
1927                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)) => {
1928                                         // The channel has already been closed, so no use bothering to care about the
1929                                         // monitor updating completing.
1930                                         let _ = self.chain_monitor.update_channel(funding_txo, update);
1931                                 },
1932                         }
1933                 }
1934         }
1935
1936         #[cfg(any(test, feature = "_test_utils"))]
1937         pub(crate) fn test_process_background_events(&self) {
1938                 self.process_background_events();
1939         }
1940
1941         /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
1942         /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
1943         /// to inform the network about the uselessness of these channels.
1944         ///
1945         /// This method handles all the details, and must be called roughly once per minute.
1946         ///
1947         /// Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
1948         pub fn timer_chan_freshness_every_min(&self) {
1949                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1950                 self.process_background_events();
1951
1952                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1953                 let channel_state = &mut *channel_state_lock;
1954                 for (_, chan) in channel_state.by_id.iter_mut() {
1955                         if chan.is_disabled_staged() && !chan.is_live() {
1956                                 if let Ok(update) = self.get_channel_update(&chan) {
1957                                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1958                                                 msg: update
1959                                         });
1960                                 }
1961                                 chan.to_fresh();
1962                         } else if chan.is_disabled_staged() && chan.is_live() {
1963                                 chan.to_fresh();
1964                         } else if chan.is_disabled_marked() {
1965                                 chan.to_disabled_staged();
1966                         }
1967                 }
1968         }
1969
1970         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1971         /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
1972         /// along the path (including in our own channel on which we received it).
1973         /// Returns false if no payment was found to fail backwards, true if the process of failing the
1974         /// HTLC backwards has been started.
1975         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, payment_secret: &Option<PaymentSecret>) -> bool {
1976                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
1977
1978                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1979                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(*payment_hash, *payment_secret));
1980                 if let Some(mut sources) = removed_source {
1981                         for htlc in sources.drain(..) {
1982                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1983                                 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
1984                                 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
1985                                         self.latest_block_height.load(Ordering::Acquire) as u32,
1986                                 ));
1987                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1988                                                 HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
1989                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: htlc_msat_height_data });
1990                         }
1991                         true
1992                 } else { false }
1993         }
1994
1995         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
1996         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
1997         // be surfaced to the user.
1998         fn fail_holding_cell_htlcs(&self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: [u8; 32]) {
1999                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
2000                         match htlc_src {
2001                                 HTLCSource::PreviousHopData(HTLCPreviousHopData { .. }) => {
2002                                         let (failure_code, onion_failure_data) =
2003                                                 match self.channel_state.lock().unwrap().by_id.entry(channel_id) {
2004                                                         hash_map::Entry::Occupied(chan_entry) => {
2005                                                                 if let Ok(upd) = self.get_channel_update(&chan_entry.get()) {
2006                                                                         (0x1000|7, upd.encode_with_len())
2007                                                                 } else {
2008                                                                         (0x4000|10, Vec::new())
2009                                                                 }
2010                                                         },
2011                                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
2012                                                 };
2013                                         let channel_state = self.channel_state.lock().unwrap();
2014                                         self.fail_htlc_backwards_internal(channel_state,
2015                                                 htlc_src, &payment_hash, HTLCFailReason::Reason { failure_code, data: onion_failure_data});
2016                                 },
2017                                 HTLCSource::OutboundRoute { .. } => {
2018                                         self.pending_events.lock().unwrap().push(
2019                                                 events::Event::PaymentFailed {
2020                                                         payment_hash,
2021                                                         rejected_by_dest: false,
2022 #[cfg(test)]
2023                                                         error_code: None,
2024 #[cfg(test)]
2025                                                         error_data: None,
2026                                                 }
2027                                         )
2028                                 },
2029                         };
2030                 }
2031         }
2032
2033         /// Fails an HTLC backwards to the sender of it to us.
2034         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
2035         /// There are several callsites that do stupid things like loop over a list of payment_hashes
2036         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
2037         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
2038         /// still-available channels.
2039         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
2040                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
2041                 //identify whether we sent it or not based on the (I presume) very different runtime
2042                 //between the branches here. We should make this async and move it into the forward HTLCs
2043                 //timer handling.
2044
2045                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
2046                 // from block_connected which may run during initialization prior to the chain_monitor
2047                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
2048                 match source {
2049                         HTLCSource::OutboundRoute { ref path, .. } => {
2050                                 log_trace!(self.logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
2051                                 mem::drop(channel_state_lock);
2052                                 match &onion_error {
2053                                         &HTLCFailReason::LightningError { ref err } => {
2054 #[cfg(test)]
2055                                                 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());
2056 #[cfg(not(test))]
2057                                                 let (channel_update, payment_retryable, _, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
2058                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
2059                                                 // process_onion_failure we should close that channel as it implies our
2060                                                 // next-hop is needlessly blaming us!
2061                                                 if let Some(update) = channel_update {
2062                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
2063                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
2064                                                                         update,
2065                                                                 }
2066                                                         );
2067                                                 }
2068                                                 self.pending_events.lock().unwrap().push(
2069                                                         events::Event::PaymentFailed {
2070                                                                 payment_hash: payment_hash.clone(),
2071                                                                 rejected_by_dest: !payment_retryable,
2072 #[cfg(test)]
2073                                                                 error_code: onion_error_code,
2074 #[cfg(test)]
2075                                                                 error_data: onion_error_data
2076                                                         }
2077                                                 );
2078                                         },
2079                                         &HTLCFailReason::Reason {
2080 #[cfg(test)]
2081                                                         ref failure_code,
2082 #[cfg(test)]
2083                                                         ref data,
2084                                                         .. } => {
2085                                                 // we get a fail_malformed_htlc from the first hop
2086                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
2087                                                 // failures here, but that would be insufficient as get_route
2088                                                 // generally ignores its view of our own channels as we provide them via
2089                                                 // ChannelDetails.
2090                                                 // TODO: For non-temporary failures, we really should be closing the
2091                                                 // channel here as we apparently can't relay through them anyway.
2092                                                 self.pending_events.lock().unwrap().push(
2093                                                         events::Event::PaymentFailed {
2094                                                                 payment_hash: payment_hash.clone(),
2095                                                                 rejected_by_dest: path.len() == 1,
2096 #[cfg(test)]
2097                                                                 error_code: Some(*failure_code),
2098 #[cfg(test)]
2099                                                                 error_data: Some(data.clone()),
2100                                                         }
2101                                                 );
2102                                         }
2103                                 }
2104                         },
2105                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret, .. }) => {
2106                                 let err_packet = match onion_error {
2107                                         HTLCFailReason::Reason { failure_code, data } => {
2108                                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
2109                                                 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
2110                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
2111                                         },
2112                                         HTLCFailReason::LightningError { err } => {
2113                                                 log_trace!(self.logger, "Failing HTLC with payment_hash {} backwards with pre-built LightningError", log_bytes!(payment_hash.0));
2114                                                 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
2115                                         }
2116                                 };
2117
2118                                 let mut forward_event = None;
2119                                 if channel_state_lock.forward_htlcs.is_empty() {
2120                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS));
2121                                 }
2122                                 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
2123                                         hash_map::Entry::Occupied(mut entry) => {
2124                                                 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
2125                                         },
2126                                         hash_map::Entry::Vacant(entry) => {
2127                                                 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
2128                                         }
2129                                 }
2130                                 mem::drop(channel_state_lock);
2131                                 if let Some(time) = forward_event {
2132                                         let mut pending_events = self.pending_events.lock().unwrap();
2133                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2134                                                 time_forwardable: time
2135                                         });
2136                                 }
2137                         },
2138                 }
2139         }
2140
2141         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
2142         /// generating message events for the net layer to claim the payment, if possible. Thus, you
2143         /// should probably kick the net layer to go send messages if this returns true!
2144         ///
2145         /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
2146         /// available within a few percent of the expected amount. This is critical for several
2147         /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
2148         /// payment_preimage without having provided the full value and b) it avoids certain
2149         /// privacy-breaking recipient-probing attacks which may reveal payment activity to
2150         /// motivated attackers.
2151         ///
2152         /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
2153         /// set. Thus, for such payments we will claim any payments which do not under-pay.
2154         ///
2155         /// May panic if called except in response to a PaymentReceived event.
2156         pub fn claim_funds(&self, payment_preimage: PaymentPreimage, payment_secret: &Option<PaymentSecret>, expected_amount: u64) -> bool {
2157                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
2158
2159                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2160
2161                 let mut channel_state = Some(self.channel_state.lock().unwrap());
2162                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&(payment_hash, *payment_secret));
2163                 if let Some(mut sources) = removed_source {
2164                         assert!(!sources.is_empty());
2165
2166                         // If we are claiming an MPP payment, we have to take special care to ensure that each
2167                         // channel exists before claiming all of the payments (inside one lock).
2168                         // Note that channel existance is sufficient as we should always get a monitor update
2169                         // which will take care of the real HTLC claim enforcement.
2170                         //
2171                         // If we find an HTLC which we would need to claim but for which we do not have a
2172                         // channel, we will fail all parts of the MPP payment. While we could wait and see if
2173                         // the sender retries the already-failed path(s), it should be a pretty rare case where
2174                         // we got all the HTLCs and then a channel closed while we were waiting for the user to
2175                         // provide the preimage, so worrying too much about the optimal handling isn't worth
2176                         // it.
2177
2178                         let (is_mpp, mut valid_mpp) = if let &Some(ref data) = &sources[0].payment_data {
2179                                 assert!(payment_secret.is_some());
2180                                 (true, data.total_msat >= expected_amount)
2181                         } else {
2182                                 assert!(payment_secret.is_none());
2183                                 (false, false)
2184                         };
2185
2186                         for htlc in sources.iter() {
2187                                 if !is_mpp || !valid_mpp { break; }
2188                                 if let None = channel_state.as_ref().unwrap().short_to_id.get(&htlc.prev_hop.short_channel_id) {
2189                                         valid_mpp = false;
2190                                 }
2191                         }
2192
2193                         let mut errs = Vec::new();
2194                         let mut claimed_any_htlcs = false;
2195                         for htlc in sources.drain(..) {
2196                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
2197                                 if (is_mpp && !valid_mpp) || (!is_mpp && (htlc.value < expected_amount || htlc.value > expected_amount * 2)) {
2198                                         let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
2199                                         htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(
2200                                                 self.latest_block_height.load(Ordering::Acquire) as u32,
2201                                         ));
2202                                         self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
2203                                                                          HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
2204                                                                          HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_height_data });
2205                                 } else {
2206                                         match self.claim_funds_from_hop(channel_state.as_mut().unwrap(), htlc.prev_hop, payment_preimage) {
2207                                                 Err(Some(e)) => {
2208                                                         if let msgs::ErrorAction::IgnoreError = e.1.err.action {
2209                                                                 // We got a temporary failure updating monitor, but will claim the
2210                                                                 // HTLC when the monitor updating is restored (or on chain).
2211                                                                 log_error!(self.logger, "Temporary failure claiming HTLC, treating as success: {}", e.1.err.err);
2212                                                                 claimed_any_htlcs = true;
2213                                                         } else { errs.push(e); }
2214                                                 },
2215                                                 Err(None) if is_mpp => unreachable!("We already checked for channel existence, we can't fail here!"),
2216                                                 Err(None) => {
2217                                                         log_warn!(self.logger, "Channel we expected to claim an HTLC from was closed.");
2218                                                 },
2219                                                 Ok(()) => claimed_any_htlcs = true,
2220                                         }
2221                                 }
2222                         }
2223
2224                         // Now that we've done the entire above loop in one lock, we can handle any errors
2225                         // which were generated.
2226                         channel_state.take();
2227
2228                         for (counterparty_node_id, err) in errs.drain(..) {
2229                                 let res: Result<(), _> = Err(err);
2230                                 let _ = handle_error!(self, res, counterparty_node_id);
2231                         }
2232
2233                         claimed_any_htlcs
2234                 } else { false }
2235         }
2236
2237         fn claim_funds_from_hop(&self, channel_state_lock: &mut MutexGuard<ChannelHolder<Signer>>, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage) -> Result<(), Option<(PublicKey, MsgHandleErrInternal)>> {
2238                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
2239                 let channel_state = &mut **channel_state_lock;
2240                 let chan_id = match channel_state.short_to_id.get(&prev_hop.short_channel_id) {
2241                         Some(chan_id) => chan_id.clone(),
2242                         None => {
2243                                 return Err(None)
2244                         }
2245                 };
2246
2247                 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(chan_id) {
2248                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2249                         match chan.get_mut().get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &self.logger) {
2250                                 Ok((msgs, monitor_option)) => {
2251                                         if let Some(monitor_update) = monitor_option {
2252                                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2253                                                         if was_frozen_for_monitor {
2254                                                                 assert!(msgs.is_none());
2255                                                         } else {
2256                                                                 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())));
2257                                                         }
2258                                                 }
2259                                         }
2260                                         if let Some((msg, commitment_signed)) = msgs {
2261                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2262                                                         node_id: chan.get().get_counterparty_node_id(),
2263                                                         updates: msgs::CommitmentUpdate {
2264                                                                 update_add_htlcs: Vec::new(),
2265                                                                 update_fulfill_htlcs: vec![msg],
2266                                                                 update_fail_htlcs: Vec::new(),
2267                                                                 update_fail_malformed_htlcs: Vec::new(),
2268                                                                 update_fee: None,
2269                                                                 commitment_signed,
2270                                                         }
2271                                                 });
2272                                         }
2273                                         return Ok(())
2274                                 },
2275                                 Err(e) => {
2276                                         // TODO: Do something with e?
2277                                         // This should only occur if we are claiming an HTLC at the same time as the
2278                                         // HTLC is being failed (eg because a block is being connected and this caused
2279                                         // an HTLC to time out). This should, of course, only occur if the user is the
2280                                         // one doing the claiming (as it being a part of a peer claim would imply we're
2281                                         // about to lose funds) and only if the lock in claim_funds was dropped as a
2282                                         // previous HTLC was failed (thus not for an MPP payment).
2283                                         debug_assert!(false, "This shouldn't be reachable except in absurdly rare cases between monitor updates and HTLC timeouts: {:?}", e);
2284                                         return Err(None)
2285                                 },
2286                         }
2287                 } else { unreachable!(); }
2288         }
2289
2290         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<Signer>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2291                 match source {
2292                         HTLCSource::OutboundRoute { .. } => {
2293                                 mem::drop(channel_state_lock);
2294                                 let mut pending_events = self.pending_events.lock().unwrap();
2295                                 pending_events.push(events::Event::PaymentSent {
2296                                         payment_preimage
2297                                 });
2298                         },
2299                         HTLCSource::PreviousHopData(hop_data) => {
2300                                 let prev_outpoint = hop_data.outpoint;
2301                                 if let Err((counterparty_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
2302                                         Ok(()) => Ok(()),
2303                                         Err(None) => {
2304                                                 let preimage_update = ChannelMonitorUpdate {
2305                                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
2306                                                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
2307                                                                 payment_preimage: payment_preimage.clone(),
2308                                                         }],
2309                                                 };
2310                                                 // We update the ChannelMonitor on the backward link, after
2311                                                 // receiving an offchain preimage event from the forward link (the
2312                                                 // event being update_fulfill_htlc).
2313                                                 if let Err(e) = self.chain_monitor.update_channel(prev_outpoint, preimage_update) {
2314                                                         log_error!(self.logger, "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
2315                                                                    payment_preimage, e);
2316                                                 }
2317                                                 Ok(())
2318                                         },
2319                                         Err(Some(res)) => Err(res),
2320                                 } {
2321                                         mem::drop(channel_state_lock);
2322                                         let res: Result<(), _> = Err(err);
2323                                         let _ = handle_error!(self, res, counterparty_node_id);
2324                                 }
2325                         },
2326                 }
2327         }
2328
2329         /// Gets the node_id held by this ChannelManager
2330         pub fn get_our_node_id(&self) -> PublicKey {
2331                 self.our_network_pubkey.clone()
2332         }
2333
2334         /// Restores a single, given channel to normal operation after a
2335         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
2336         /// operation.
2337         ///
2338         /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
2339         /// fully committed in every copy of the given channels' ChannelMonitors.
2340         ///
2341         /// Note that there is no effect to calling with a highest_applied_update_id other than the
2342         /// current latest ChannelMonitorUpdate and one call to this function after multiple
2343         /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
2344         /// exists largely only to prevent races between this and concurrent update_monitor calls.
2345         ///
2346         /// Thus, the anticipated use is, at a high level:
2347         ///  1) You register a chain::Watch with this ChannelManager,
2348         ///  2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
2349         ///     said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
2350         ///     any time it cannot do so instantly,
2351         ///  3) update(s) are applied to each remote copy of a ChannelMonitor,
2352         ///  4) once all remote copies are updated, you call this function with the update_id that
2353         ///     completed, and once it is the latest the Channel will be re-enabled.
2354         pub fn channel_monitor_updated(&self, funding_txo: &OutPoint, highest_applied_update_id: u64) {
2355                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
2356
2357                 let mut close_results = Vec::new();
2358                 let mut htlc_forwards = Vec::new();
2359                 let mut htlc_failures = Vec::new();
2360                 let mut pending_events = Vec::new();
2361
2362                 {
2363                         let mut channel_lock = self.channel_state.lock().unwrap();
2364                         let channel_state = &mut *channel_lock;
2365                         let short_to_id = &mut channel_state.short_to_id;
2366                         let pending_msg_events = &mut channel_state.pending_msg_events;
2367                         let channel = match channel_state.by_id.get_mut(&funding_txo.to_channel_id()) {
2368                                 Some(chan) => chan,
2369                                 None => return,
2370                         };
2371                         if !channel.is_awaiting_monitor_update() || channel.get_latest_monitor_update_id() != highest_applied_update_id {
2372                                 return;
2373                         }
2374
2375                         let (raa, commitment_update, order, pending_forwards, mut pending_failures, needs_broadcast_safe, funding_locked) = channel.monitor_updating_restored(&self.logger);
2376                         if !pending_forwards.is_empty() {
2377                                 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), funding_txo.clone(), pending_forwards));
2378                         }
2379                         htlc_failures.append(&mut pending_failures);
2380
2381                         macro_rules! handle_cs { () => {
2382                                 if let Some(update) = commitment_update {
2383                                         pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2384                                                 node_id: channel.get_counterparty_node_id(),
2385                                                 updates: update,
2386                                         });
2387                                 }
2388                         } }
2389                         macro_rules! handle_raa { () => {
2390                                 if let Some(revoke_and_ack) = raa {
2391                                         pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2392                                                 node_id: channel.get_counterparty_node_id(),
2393                                                 msg: revoke_and_ack,
2394                                         });
2395                                 }
2396                         } }
2397                         match order {
2398                                 RAACommitmentOrder::CommitmentFirst => {
2399                                         handle_cs!();
2400                                         handle_raa!();
2401                                 },
2402                                 RAACommitmentOrder::RevokeAndACKFirst => {
2403                                         handle_raa!();
2404                                         handle_cs!();
2405                                 },
2406                         }
2407                         if needs_broadcast_safe {
2408                                 pending_events.push(events::Event::FundingBroadcastSafe {
2409                                         funding_txo: channel.get_funding_txo().unwrap(),
2410                                         user_channel_id: channel.get_user_id(),
2411                                 });
2412                         }
2413                         if let Some(msg) = funding_locked {
2414                                 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2415                                         node_id: channel.get_counterparty_node_id(),
2416                                         msg,
2417                                 });
2418                                 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2419                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2420                                                 node_id: channel.get_counterparty_node_id(),
2421                                                 msg: announcement_sigs,
2422                                         });
2423                                 }
2424                                 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2425                         }
2426                 }
2427
2428                 self.pending_events.lock().unwrap().append(&mut pending_events);
2429
2430                 for failure in htlc_failures.drain(..) {
2431                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2432                 }
2433                 self.forward_htlcs(&mut htlc_forwards[..]);
2434
2435                 for res in close_results.drain(..) {
2436                         self.finish_force_close_channel(res);
2437                 }
2438         }
2439
2440         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
2441                 if msg.chain_hash != self.genesis_hash {
2442                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
2443                 }
2444
2445                 let channel = Channel::new_from_req(&self.fee_estimator, &self.keys_manager, counterparty_node_id.clone(), their_features, msg, 0, &self.default_configuration)
2446                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
2447                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2448                 let channel_state = &mut *channel_state_lock;
2449                 match channel_state.by_id.entry(channel.channel_id()) {
2450                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!".to_owned(), msg.temporary_channel_id.clone())),
2451                         hash_map::Entry::Vacant(entry) => {
2452                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
2453                                         node_id: counterparty_node_id.clone(),
2454                                         msg: channel.get_accept_channel(),
2455                                 });
2456                                 entry.insert(channel);
2457                         }
2458                 }
2459                 Ok(())
2460         }
2461
2462         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
2463                 let (value, output_script, user_id) = {
2464                         let mut channel_lock = self.channel_state.lock().unwrap();
2465                         let channel_state = &mut *channel_lock;
2466                         match channel_state.by_id.entry(msg.temporary_channel_id) {
2467                                 hash_map::Entry::Occupied(mut chan) => {
2468                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2469                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2470                                         }
2471                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration, their_features), channel_state, chan);
2472                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
2473                                 },
2474                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2475                         }
2476                 };
2477                 let mut pending_events = self.pending_events.lock().unwrap();
2478                 pending_events.push(events::Event::FundingGenerationReady {
2479                         temporary_channel_id: msg.temporary_channel_id,
2480                         channel_value_satoshis: value,
2481                         output_script,
2482                         user_channel_id: user_id,
2483                 });
2484                 Ok(())
2485         }
2486
2487         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
2488                 let ((funding_msg, monitor), mut chan) = {
2489                         let last_block_hash = *self.last_block_hash.read().unwrap();
2490                         let mut channel_lock = self.channel_state.lock().unwrap();
2491                         let channel_state = &mut *channel_lock;
2492                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
2493                                 hash_map::Entry::Occupied(mut chan) => {
2494                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2495                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
2496                                         }
2497                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg, last_block_hash, &self.logger), channel_state, chan), chan.remove())
2498                                 },
2499                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
2500                         }
2501                 };
2502                 // Because we have exclusive ownership of the channel here we can release the channel_state
2503                 // lock before watch_channel
2504                 if let Err(e) = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor) {
2505                         match e {
2506                                 ChannelMonitorUpdateErr::PermanentFailure => {
2507                                         // Note that we reply with the new channel_id in error messages if we gave up on the
2508                                         // channel, not the temporary_channel_id. This is compatible with ourselves, but the
2509                                         // spec is somewhat ambiguous here. Not a huge deal since we'll send error messages for
2510                                         // any messages referencing a previously-closed channel anyway.
2511                                         // We do not do a force-close here as that would generate a monitor update for
2512                                         // a monitor that we didn't manage to store (and that we don't care about - we
2513                                         // don't respond with the funding_signed so the channel can never go on chain).
2514                                         let (_monitor_update, failed_htlcs) = chan.force_shutdown(true);
2515                                         assert!(failed_htlcs.is_empty());
2516                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("ChannelMonitor storage failure".to_owned(), funding_msg.channel_id));
2517                                 },
2518                                 ChannelMonitorUpdateErr::TemporaryFailure => {
2519                                         // There's no problem signing a counterparty's funding transaction if our monitor
2520                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
2521                                         // accepted payment from yet. We do, however, need to wait to send our funding_locked
2522                                         // until we have persisted our monitor.
2523                                         chan.monitor_update_failed(false, false, Vec::new(), Vec::new());
2524                                 },
2525                         }
2526                 }
2527                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2528                 let channel_state = &mut *channel_state_lock;
2529                 match channel_state.by_id.entry(funding_msg.channel_id) {
2530                         hash_map::Entry::Occupied(_) => {
2531                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id".to_owned(), funding_msg.channel_id))
2532                         },
2533                         hash_map::Entry::Vacant(e) => {
2534                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
2535                                         node_id: counterparty_node_id.clone(),
2536                                         msg: funding_msg,
2537                                 });
2538                                 e.insert(chan);
2539                         }
2540                 }
2541                 Ok(())
2542         }
2543
2544         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
2545                 let (funding_txo, user_id) = {
2546                         let last_block_hash = *self.last_block_hash.read().unwrap();
2547                         let mut channel_lock = self.channel_state.lock().unwrap();
2548                         let channel_state = &mut *channel_lock;
2549                         match channel_state.by_id.entry(msg.channel_id) {
2550                                 hash_map::Entry::Occupied(mut chan) => {
2551                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2552                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2553                                         }
2554                                         let monitor = match chan.get_mut().funding_signed(&msg, last_block_hash, &self.logger) {
2555                                                 Ok(update) => update,
2556                                                 Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
2557                                         };
2558                                         if let Err(e) = self.chain_monitor.watch_channel(chan.get().get_funding_txo().unwrap(), monitor) {
2559                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, false, false);
2560                                         }
2561                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
2562                                 },
2563                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2564                         }
2565                 };
2566                 let mut pending_events = self.pending_events.lock().unwrap();
2567                 pending_events.push(events::Event::FundingBroadcastSafe {
2568                         funding_txo,
2569                         user_channel_id: user_id,
2570                 });
2571                 Ok(())
2572         }
2573
2574         fn internal_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
2575                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2576                 let channel_state = &mut *channel_state_lock;
2577                 match channel_state.by_id.entry(msg.channel_id) {
2578                         hash_map::Entry::Occupied(mut chan) => {
2579                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2580                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2581                                 }
2582                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
2583                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
2584                                         log_trace!(self.logger, "Sending announcement_signatures for {} in response to funding_locked", log_bytes!(chan.get().channel_id()));
2585                                         // If we see locking block before receiving remote funding_locked, we broadcast our
2586                                         // announcement_sigs at remote funding_locked reception. If we receive remote
2587                                         // funding_locked before seeing locking block, we broadcast our announcement_sigs at locking
2588                                         // block connection. We should guanrantee to broadcast announcement_sigs to our peer whatever
2589                                         // the order of the events but our peer may not receive it due to disconnection. The specs
2590                                         // lacking an acknowledgement for announcement_sigs we may have to re-send them at peer
2591                                         // connection in the future if simultaneous misses by both peers due to network/hardware
2592                                         // failures is an issue. Note, to achieve its goal, only one of the announcement_sigs needs
2593                                         // to be received, from then sigs are going to be flood to the whole network.
2594                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2595                                                 node_id: counterparty_node_id.clone(),
2596                                                 msg: announcement_sigs,
2597                                         });
2598                                 }
2599                                 Ok(())
2600                         },
2601                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2602                 }
2603         }
2604
2605         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
2606                 let (mut dropped_htlcs, chan_option) = {
2607                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2608                         let channel_state = &mut *channel_state_lock;
2609
2610                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2611                                 hash_map::Entry::Occupied(mut chan_entry) => {
2612                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2613                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2614                                         }
2615                                         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);
2616                                         if let Some(msg) = shutdown {
2617                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2618                                                         node_id: counterparty_node_id.clone(),
2619                                                         msg,
2620                                                 });
2621                                         }
2622                                         if let Some(msg) = closing_signed {
2623                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2624                                                         node_id: counterparty_node_id.clone(),
2625                                                         msg,
2626                                                 });
2627                                         }
2628                                         if chan_entry.get().is_shutdown() {
2629                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2630                                                         channel_state.short_to_id.remove(&short_id);
2631                                                 }
2632                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
2633                                         } else { (dropped_htlcs, None) }
2634                                 },
2635                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2636                         }
2637                 };
2638                 for htlc_source in dropped_htlcs.drain(..) {
2639                         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() });
2640                 }
2641                 if let Some(chan) = chan_option {
2642                         if let Ok(update) = self.get_channel_update(&chan) {
2643                                 let mut channel_state = self.channel_state.lock().unwrap();
2644                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2645                                         msg: update
2646                                 });
2647                         }
2648                 }
2649                 Ok(())
2650         }
2651
2652         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2653                 let (tx, chan_option) = {
2654                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2655                         let channel_state = &mut *channel_state_lock;
2656                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2657                                 hash_map::Entry::Occupied(mut chan_entry) => {
2658                                         if chan_entry.get().get_counterparty_node_id() != *counterparty_node_id {
2659                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2660                                         }
2661                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&self.fee_estimator, &msg), channel_state, chan_entry);
2662                                         if let Some(msg) = closing_signed {
2663                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2664                                                         node_id: counterparty_node_id.clone(),
2665                                                         msg,
2666                                                 });
2667                                         }
2668                                         if tx.is_some() {
2669                                                 // We're done with this channel, we've got a signed closing transaction and
2670                                                 // will send the closing_signed back to the remote peer upon return. This
2671                                                 // also implies there are no pending HTLCs left on the channel, so we can
2672                                                 // fully delete it from tracking (the channel monitor is still around to
2673                                                 // watch for old state broadcasts)!
2674                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2675                                                         channel_state.short_to_id.remove(&short_id);
2676                                                 }
2677                                                 (tx, Some(chan_entry.remove_entry().1))
2678                                         } else { (tx, None) }
2679                                 },
2680                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2681                         }
2682                 };
2683                 if let Some(broadcast_tx) = tx {
2684                         log_trace!(self.logger, "Broadcast onchain {}", log_tx!(broadcast_tx));
2685                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2686                 }
2687                 if let Some(chan) = chan_option {
2688                         if let Ok(update) = self.get_channel_update(&chan) {
2689                                 let mut channel_state = self.channel_state.lock().unwrap();
2690                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2691                                         msg: update
2692                                 });
2693                         }
2694                 }
2695                 Ok(())
2696         }
2697
2698         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2699                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2700                 //determine the state of the payment based on our response/if we forward anything/the time
2701                 //we take to respond. We should take care to avoid allowing such an attack.
2702                 //
2703                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2704                 //us repeatedly garbled in different ways, and compare our error messages, which are
2705                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
2706                 //but we should prevent it anyway.
2707
2708                 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2709                 let channel_state = &mut *channel_state_lock;
2710
2711                 match channel_state.by_id.entry(msg.channel_id) {
2712                         hash_map::Entry::Occupied(mut chan) => {
2713                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2714                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2715                                 }
2716
2717                                 let create_pending_htlc_status = |chan: &Channel<Signer>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
2718                                         // Ensure error_code has the UPDATE flag set, since by default we send a
2719                                         // channel update along as part of failing the HTLC.
2720                                         assert!((error_code & 0x1000) != 0);
2721                                         // If the update_add is completely bogus, the call will Err and we will close,
2722                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2723                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2724                                         match pending_forward_info {
2725                                                 PendingHTLCStatus::Forward(PendingHTLCInfo { ref incoming_shared_secret, .. }) => {
2726                                                         let reason = if let Ok(upd) = self.get_channel_update(chan) {
2727                                                                 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, error_code, &{
2728                                                                         let mut res = Vec::with_capacity(8 + 128);
2729                                                                         // TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
2730                                                                         res.extend_from_slice(&byte_utils::be16_to_array(0));
2731                                                                         res.extend_from_slice(&upd.encode_with_len()[..]);
2732                                                                         res
2733                                                                 }[..])
2734                                                         } else {
2735                                                                 // The only case where we'd be unable to
2736                                                                 // successfully get a channel update is if the
2737                                                                 // channel isn't in the fully-funded state yet,
2738                                                                 // implying our counterparty is trying to route
2739                                                                 // payments over the channel back to themselves
2740                                                                 // (cause no one else should know the short_id
2741                                                                 // is a lightning channel yet). We should have
2742                                                                 // no problem just calling this
2743                                                                 // unknown_next_peer (0x4000|10).
2744                                                                 onion_utils::build_first_hop_failure_packet(incoming_shared_secret, 0x4000|10, &[])
2745                                                         };
2746                                                         let msg = msgs::UpdateFailHTLC {
2747                                                                 channel_id: msg.channel_id,
2748                                                                 htlc_id: msg.htlc_id,
2749                                                                 reason
2750                                                         };
2751                                                         PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
2752                                                 },
2753                                                 _ => pending_forward_info
2754                                         }
2755                                 };
2756                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.logger), channel_state, chan);
2757                         },
2758                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2759                 }
2760                 Ok(())
2761         }
2762
2763         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2764                 let mut channel_lock = self.channel_state.lock().unwrap();
2765                 let htlc_source = {
2766                         let channel_state = &mut *channel_lock;
2767                         match channel_state.by_id.entry(msg.channel_id) {
2768                                 hash_map::Entry::Occupied(mut chan) => {
2769                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2770                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2771                                         }
2772                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2773                                 },
2774                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2775                         }
2776                 };
2777                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2778                 Ok(())
2779         }
2780
2781         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2782                 let mut channel_lock = self.channel_state.lock().unwrap();
2783                 let channel_state = &mut *channel_lock;
2784                 match channel_state.by_id.entry(msg.channel_id) {
2785                         hash_map::Entry::Occupied(mut chan) => {
2786                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2787                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2788                                 }
2789                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::LightningError { err: msg.reason.clone() }), channel_state, chan);
2790                         },
2791                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2792                 }
2793                 Ok(())
2794         }
2795
2796         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2797                 let mut channel_lock = self.channel_state.lock().unwrap();
2798                 let channel_state = &mut *channel_lock;
2799                 match channel_state.by_id.entry(msg.channel_id) {
2800                         hash_map::Entry::Occupied(mut chan) => {
2801                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2802                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2803                                 }
2804                                 if (msg.failure_code & 0x8000) == 0 {
2805                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
2806                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
2807                                 }
2808                                 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);
2809                                 Ok(())
2810                         },
2811                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2812                 }
2813         }
2814
2815         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2816                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2817                 let channel_state = &mut *channel_state_lock;
2818                 match channel_state.by_id.entry(msg.channel_id) {
2819                         hash_map::Entry::Occupied(mut chan) => {
2820                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2821                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2822                                 }
2823                                 let (revoke_and_ack, commitment_signed, closing_signed, monitor_update) =
2824                                         match chan.get_mut().commitment_signed(&msg, &self.fee_estimator, &self.logger) {
2825                                                 Err((None, e)) => try_chan_entry!(self, Err(e), channel_state, chan),
2826                                                 Err((Some(update), e)) => {
2827                                                         assert!(chan.get().is_awaiting_monitor_update());
2828                                                         let _ = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), update);
2829                                                         try_chan_entry!(self, Err(e), channel_state, chan);
2830                                                         unreachable!();
2831                                                 },
2832                                                 Ok(res) => res
2833                                         };
2834                                 if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2835                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
2836                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2837                                 }
2838                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2839                                         node_id: counterparty_node_id.clone(),
2840                                         msg: revoke_and_ack,
2841                                 });
2842                                 if let Some(msg) = commitment_signed {
2843                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2844                                                 node_id: counterparty_node_id.clone(),
2845                                                 updates: msgs::CommitmentUpdate {
2846                                                         update_add_htlcs: Vec::new(),
2847                                                         update_fulfill_htlcs: Vec::new(),
2848                                                         update_fail_htlcs: Vec::new(),
2849                                                         update_fail_malformed_htlcs: Vec::new(),
2850                                                         update_fee: None,
2851                                                         commitment_signed: msg,
2852                                                 },
2853                                         });
2854                                 }
2855                                 if let Some(msg) = closing_signed {
2856                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2857                                                 node_id: counterparty_node_id.clone(),
2858                                                 msg,
2859                                         });
2860                                 }
2861                                 Ok(())
2862                         },
2863                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2864                 }
2865         }
2866
2867         #[inline]
2868         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, Vec<(PendingHTLCInfo, u64)>)]) {
2869                 for &mut (prev_short_channel_id, prev_funding_outpoint, ref mut pending_forwards) in per_source_pending_forwards {
2870                         let mut forward_event = None;
2871                         if !pending_forwards.is_empty() {
2872                                 let mut channel_state = self.channel_state.lock().unwrap();
2873                                 if channel_state.forward_htlcs.is_empty() {
2874                                         forward_event = Some(Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS))
2875                                 }
2876                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2877                                         match channel_state.forward_htlcs.entry(match forward_info.routing {
2878                                                         PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
2879                                                         PendingHTLCRouting::Receive { .. } => 0,
2880                                         }) {
2881                                                 hash_map::Entry::Occupied(mut entry) => {
2882                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2883                                                                                                         prev_htlc_id, forward_info });
2884                                                 },
2885                                                 hash_map::Entry::Vacant(entry) => {
2886                                                         entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_funding_outpoint,
2887                                                                                                      prev_htlc_id, forward_info }));
2888                                                 }
2889                                         }
2890                                 }
2891                         }
2892                         match forward_event {
2893                                 Some(time) => {
2894                                         let mut pending_events = self.pending_events.lock().unwrap();
2895                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2896                                                 time_forwardable: time
2897                                         });
2898                                 }
2899                                 None => {},
2900                         }
2901                 }
2902         }
2903
2904         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2905                 let mut htlcs_to_fail = Vec::new();
2906                 let res = loop {
2907                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2908                         let channel_state = &mut *channel_state_lock;
2909                         match channel_state.by_id.entry(msg.channel_id) {
2910                                 hash_map::Entry::Occupied(mut chan) => {
2911                                         if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2912                                                 break Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2913                                         }
2914                                         let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2915                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, monitor_update, htlcs_to_fail_in) =
2916                                                 break_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &self.fee_estimator, &self.logger), channel_state, chan);
2917                                         htlcs_to_fail = htlcs_to_fail_in;
2918                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
2919                                                 if was_frozen_for_monitor {
2920                                                         assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2921                                                         break Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA".to_owned()));
2922                                                 } else {
2923                                                         if let Err(e) = handle_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures) {
2924                                                                 break Err(e);
2925                                                         } else { unreachable!(); }
2926                                                 }
2927                                         }
2928                                         if let Some(updates) = commitment_update {
2929                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2930                                                         node_id: counterparty_node_id.clone(),
2931                                                         updates,
2932                                                 });
2933                                         }
2934                                         if let Some(msg) = closing_signed {
2935                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2936                                                         node_id: counterparty_node_id.clone(),
2937                                                         msg,
2938                                                 });
2939                                         }
2940                                         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()))
2941                                 },
2942                                 hash_map::Entry::Vacant(_) => break Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2943                         }
2944                 };
2945                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id);
2946                 match res {
2947                         Ok((pending_forwards, mut pending_failures, short_channel_id, channel_outpoint)) => {
2948                                 for failure in pending_failures.drain(..) {
2949                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2950                                 }
2951                                 self.forward_htlcs(&mut [(short_channel_id, channel_outpoint, pending_forwards)]);
2952                                 Ok(())
2953                         },
2954                         Err(e) => Err(e)
2955                 }
2956         }
2957
2958         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2959                 let mut channel_lock = self.channel_state.lock().unwrap();
2960                 let channel_state = &mut *channel_lock;
2961                 match channel_state.by_id.entry(msg.channel_id) {
2962                         hash_map::Entry::Occupied(mut chan) => {
2963                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2964                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2965                                 }
2966                                 try_chan_entry!(self, chan.get_mut().update_fee(&self.fee_estimator, &msg), channel_state, chan);
2967                         },
2968                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
2969                 }
2970                 Ok(())
2971         }
2972
2973         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2974                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2975                 let channel_state = &mut *channel_state_lock;
2976
2977                 match channel_state.by_id.entry(msg.channel_id) {
2978                         hash_map::Entry::Occupied(mut chan) => {
2979                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
2980                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
2981                                 }
2982                                 if !chan.get().is_usable() {
2983                                         return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
2984                                 }
2985
2986                                 let our_node_id = self.get_our_node_id();
2987                                 let (announcement, our_bitcoin_sig) =
2988                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2989
2990                                 let were_node_one = announcement.node_id_1 == our_node_id;
2991                                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
2992                                 {
2993                                         let their_node_key = if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 };
2994                                         let their_bitcoin_key = if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 };
2995                                         match (self.secp_ctx.verify(&msghash, &msg.node_signature, their_node_key),
2996                                                    self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, their_bitcoin_key)) {
2997                                                 (Err(e), _) => {
2998                                                         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));
2999                                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
3000                                                 },
3001                                                 (_, Err(e)) => {
3002                                                         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));
3003                                                         try_chan_entry!(self, Err(chan_err), channel_state, chan);
3004                                                 },
3005                                                 _ => {}
3006                                         }
3007                                 }
3008
3009                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
3010
3011                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
3012                                         msg: msgs::ChannelAnnouncement {
3013                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
3014                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
3015                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
3016                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
3017                                                 contents: announcement,
3018                                         },
3019                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
3020                                 });
3021                         },
3022                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3023                 }
3024                 Ok(())
3025         }
3026
3027         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<(), MsgHandleErrInternal> {
3028                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3029                 let channel_state = &mut *channel_state_lock;
3030                 let chan_id = match channel_state.short_to_id.get(&msg.contents.short_channel_id) {
3031                         Some(chan_id) => chan_id.clone(),
3032                         None => {
3033                                 // It's not a local channel
3034                                 return Ok(())
3035                         }
3036                 };
3037                 match channel_state.by_id.entry(chan_id) {
3038                         hash_map::Entry::Occupied(mut chan) => {
3039                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3040                                         // TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
3041                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), chan_id));
3042                                 }
3043                                 try_chan_entry!(self, chan.get_mut().channel_update(&msg), channel_state, chan);
3044                         },
3045                         hash_map::Entry::Vacant(_) => unreachable!()
3046                 }
3047                 Ok(())
3048         }
3049
3050         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
3051                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3052                 let channel_state = &mut *channel_state_lock;
3053
3054                 match channel_state.by_id.entry(msg.channel_id) {
3055                         hash_map::Entry::Occupied(mut chan) => {
3056                                 if chan.get().get_counterparty_node_id() != *counterparty_node_id {
3057                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
3058                                 }
3059                                 // Currently, we expect all holding cell update_adds to be dropped on peer
3060                                 // disconnect, so Channel's reestablish will never hand us any holding cell
3061                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
3062                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
3063                                 let (funding_locked, revoke_and_ack, commitment_update, monitor_update_opt, mut order, shutdown) =
3064                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg, &self.logger), channel_state, chan);
3065                                 if let Some(monitor_update) = monitor_update_opt {
3066                                         if let Err(e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3067                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
3068                                                 // for the messages it returns, but if we're setting what messages to
3069                                                 // re-transmit on monitor update success, we need to make sure it is sane.
3070                                                 if revoke_and_ack.is_none() {
3071                                                         order = RAACommitmentOrder::CommitmentFirst;
3072                                                 }
3073                                                 if commitment_update.is_none() {
3074                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
3075                                                 }
3076                                                 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
3077                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
3078                                         }
3079                                 }
3080                                 if let Some(msg) = funding_locked {
3081                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3082                                                 node_id: counterparty_node_id.clone(),
3083                                                 msg
3084                                         });
3085                                 }
3086                                 macro_rules! send_raa { () => {
3087                                         if let Some(msg) = revoke_and_ack {
3088                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
3089                                                         node_id: counterparty_node_id.clone(),
3090                                                         msg
3091                                                 });
3092                                         }
3093                                 } }
3094                                 macro_rules! send_cu { () => {
3095                                         if let Some(updates) = commitment_update {
3096                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3097                                                         node_id: counterparty_node_id.clone(),
3098                                                         updates
3099                                                 });
3100                                         }
3101                                 } }
3102                                 match order {
3103                                         RAACommitmentOrder::RevokeAndACKFirst => {
3104                                                 send_raa!();
3105                                                 send_cu!();
3106                                         },
3107                                         RAACommitmentOrder::CommitmentFirst => {
3108                                                 send_cu!();
3109                                                 send_raa!();
3110                                         },
3111                                 }
3112                                 if let Some(msg) = shutdown {
3113                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
3114                                                 node_id: counterparty_node_id.clone(),
3115                                                 msg,
3116                                         });
3117                                 }
3118                                 Ok(())
3119                         },
3120                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
3121                 }
3122         }
3123
3124         /// Begin Update fee process. Allowed only on an outbound channel.
3125         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
3126         /// PeerManager::process_events afterwards.
3127         /// Note: This API is likely to change!
3128         /// (C-not exported) Cause its doc(hidden) anyway
3129         #[doc(hidden)]
3130         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u32) -> Result<(), APIError> {
3131                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3132                 let counterparty_node_id;
3133                 let err: Result<(), _> = loop {
3134                         let mut channel_state_lock = self.channel_state.lock().unwrap();
3135                         let channel_state = &mut *channel_state_lock;
3136
3137                         match channel_state.by_id.entry(channel_id) {
3138                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: format!("Failed to find corresponding channel for id {}", channel_id.to_hex())}),
3139                                 hash_map::Entry::Occupied(mut chan) => {
3140                                         if !chan.get().is_outbound() {
3141                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel".to_owned()});
3142                                         }
3143                                         if chan.get().is_awaiting_monitor_update() {
3144                                                 return Err(APIError::MonitorUpdateFailed);
3145                                         }
3146                                         if !chan.get().is_live() {
3147                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected".to_owned()});
3148                                         }
3149                                         counterparty_node_id = chan.get().get_counterparty_node_id();
3150                                         if let Some((update_fee, commitment_signed, monitor_update)) =
3151                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw, &self.logger), channel_state, chan)
3152                                         {
3153                                                 if let Err(_e) = self.chain_monitor.update_channel(chan.get().get_funding_txo().unwrap(), monitor_update) {
3154                                                         unimplemented!();
3155                                                 }
3156                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
3157                                                         node_id: chan.get().get_counterparty_node_id(),
3158                                                         updates: msgs::CommitmentUpdate {
3159                                                                 update_add_htlcs: Vec::new(),
3160                                                                 update_fulfill_htlcs: Vec::new(),
3161                                                                 update_fail_htlcs: Vec::new(),
3162                                                                 update_fail_malformed_htlcs: Vec::new(),
3163                                                                 update_fee: Some(update_fee),
3164                                                                 commitment_signed,
3165                                                         },
3166                                                 });
3167                                         }
3168                                 },
3169                         }
3170                         return Ok(())
3171                 };
3172
3173                 match handle_error!(self, err, counterparty_node_id) {
3174                         Ok(_) => unreachable!(),
3175                         Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
3176                 }
3177         }
3178
3179         /// Process pending events from the `chain::Watch`.
3180         fn process_pending_monitor_events(&self) {
3181                 let mut failed_channels = Vec::new();
3182                 {
3183                         for monitor_event in self.chain_monitor.release_pending_monitor_events() {
3184                                 match monitor_event {
3185                                         MonitorEvent::HTLCEvent(htlc_update) => {
3186                                                 if let Some(preimage) = htlc_update.payment_preimage {
3187                                                         log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
3188                                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3189                                                 } else {
3190                                                         log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
3191                                                         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() });
3192                                                 }
3193                                         },
3194                                         MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
3195                                                 let mut channel_lock = self.channel_state.lock().unwrap();
3196                                                 let channel_state = &mut *channel_lock;
3197                                                 let by_id = &mut channel_state.by_id;
3198                                                 let short_to_id = &mut channel_state.short_to_id;
3199                                                 let pending_msg_events = &mut channel_state.pending_msg_events;
3200                                                 if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
3201                                                         if let Some(short_id) = chan.get_short_channel_id() {
3202                                                                 short_to_id.remove(&short_id);
3203                                                         }
3204                                                         failed_channels.push(chan.force_shutdown(false));
3205                                                         if let Ok(update) = self.get_channel_update(&chan) {
3206                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3207                                                                         msg: update
3208                                                                 });
3209                                                         }
3210                                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
3211                                                                 node_id: chan.get_counterparty_node_id(),
3212                                                                 action: msgs::ErrorAction::SendErrorMessage {
3213                                                                         msg: msgs::ErrorMessage { channel_id: chan.channel_id(), data: "Channel force-closed".to_owned() }
3214                                                                 },
3215                                                         });
3216                                                 }
3217                                         },
3218                                 }
3219                         }
3220                 }
3221
3222                 for failure in failed_channels.drain(..) {
3223                         self.finish_force_close_channel(failure);
3224                 }
3225         }
3226
3227         /// Handle a list of channel failures during a block_connected or block_disconnected call,
3228         /// pushing the channel monitor update (if any) to the background events queue and removing the
3229         /// Channel object.
3230         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
3231                 for mut failure in failed_channels.drain(..) {
3232                         // Either a commitment transactions has been confirmed on-chain or
3233                         // Channel::block_disconnected detected that the funding transaction has been
3234                         // reorganized out of the main chain.
3235                         // We cannot broadcast our latest local state via monitor update (as
3236                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
3237                         // so we track the update internally and handle it when the user next calls
3238                         // timer_chan_freshness_every_min, guaranteeing we're running normally.
3239                         if let Some((funding_txo, update)) = failure.0.take() {
3240                                 assert_eq!(update.updates.len(), 1);
3241                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
3242                                         assert!(should_broadcast);
3243                                 } else { unreachable!(); }
3244                                 self.pending_background_events.lock().unwrap().push(BackgroundEvent::ClosingMonitorUpdate((funding_txo, update)));
3245                         }
3246                         self.finish_force_close_channel(failure);
3247                 }
3248         }
3249 }
3250
3251 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<Signer, M, T, K, F, L>
3252         where M::Target: chain::Watch<Signer>,
3253         T::Target: BroadcasterInterface,
3254         K::Target: KeysInterface<Signer = Signer>,
3255         F::Target: FeeEstimator,
3256                                 L::Target: Logger,
3257 {
3258         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
3259                 //TODO: This behavior should be documented. It's non-intuitive that we query
3260                 // ChannelMonitors when clearing other events.
3261                 self.process_pending_monitor_events();
3262
3263                 let mut ret = Vec::new();
3264                 let mut channel_state = self.channel_state.lock().unwrap();
3265                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
3266                 ret
3267         }
3268 }
3269
3270 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> EventsProvider for ChannelManager<Signer, M, T, K, F, L>
3271         where M::Target: chain::Watch<Signer>,
3272         T::Target: BroadcasterInterface,
3273         K::Target: KeysInterface<Signer = Signer>,
3274         F::Target: FeeEstimator,
3275                                 L::Target: Logger,
3276 {
3277         fn get_and_clear_pending_events(&self) -> Vec<Event> {
3278                 //TODO: This behavior should be documented. It's non-intuitive that we query
3279                 // ChannelMonitors when clearing other events.
3280                 self.process_pending_monitor_events();
3281
3282                 let mut ret = Vec::new();
3283                 let mut pending_events = self.pending_events.lock().unwrap();
3284                 mem::swap(&mut ret, &mut *pending_events);
3285                 ret
3286         }
3287 }
3288
3289 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> chain::Listen for ChannelManager<Signer, M, T, K, F, L>
3290 where
3291         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         fn block_connected(&self, block: &Block, height: u32) {
3298                 assert_eq!(*self.last_block_hash.read().unwrap(), block.header.prev_blockhash,
3299                         "Blocks must be connected in chain-order - the connected header must build on the last connected header");
3300                 assert_eq!(self.latest_block_height.load(Ordering::Acquire) as u64, height as u64 - 1,
3301                         "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
3302                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
3303                 self.transactions_confirmed(&block.header, height, &txdata);
3304                 self.update_best_block(&block.header, height);
3305         }
3306
3307         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3308                 assert_eq!(*self.last_block_hash.read().unwrap(), header.block_hash(),
3309                         "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
3310
3311                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3312                 let new_height = self.latest_block_height.fetch_sub(1, Ordering::AcqRel) as u32 - 1;
3313                 assert_eq!(new_height, height - 1,
3314                         "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
3315                 *self.last_block_hash.write().unwrap() = header.prev_blockhash;
3316
3317                 self.do_chain_event(new_height, |channel| channel.update_best_block(new_height, header.time));
3318         }
3319 }
3320
3321 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<Signer, M, T, K, F, L>
3322         where M::Target: chain::Watch<Signer>,
3323         T::Target: BroadcasterInterface,
3324         K::Target: KeysInterface<Signer = Signer>,
3325         F::Target: FeeEstimator,
3326         L::Target: Logger,
3327 {
3328         fn do_chain_event<FN: Fn(&mut Channel<Signer>) -> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), msgs::ErrorMessage>>
3329                         (&self, height: u32, f: FN) {
3330                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3331                 // during initialization prior to the chain_monitor being fully configured in some cases.
3332                 // See the docs for `ChannelManagerReadArgs` for more.
3333
3334                 let mut failed_channels = Vec::new();
3335                 let mut timed_out_htlcs = Vec::new();
3336                 {
3337                         let mut channel_lock = self.channel_state.lock().unwrap();
3338                         let channel_state = &mut *channel_lock;
3339                         let short_to_id = &mut channel_state.short_to_id;
3340                         let pending_msg_events = &mut channel_state.pending_msg_events;
3341                         channel_state.by_id.retain(|_, channel| {
3342                                 let res = f(channel);
3343                                 if let Ok((chan_res, mut timed_out_pending_htlcs)) = res {
3344                                         for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
3345                                                 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
3346                                                 timed_out_htlcs.push((source, payment_hash,  HTLCFailReason::Reason {
3347                                                         failure_code: 0x1000 | 14, // expiry_too_soon, or at least it is now
3348                                                         data: chan_update,
3349                                                 }));
3350                                         }
3351                                         if let Some(funding_locked) = chan_res {
3352                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
3353                                                         node_id: channel.get_counterparty_node_id(),
3354                                                         msg: funding_locked,
3355                                                 });
3356                                                 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
3357                                                         log_trace!(self.logger, "Sending funding_locked and announcement_signatures for {}", log_bytes!(channel.channel_id()));
3358                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
3359                                                                 node_id: channel.get_counterparty_node_id(),
3360                                                                 msg: announcement_sigs,
3361                                                         });
3362                                                 } else {
3363                                                         log_trace!(self.logger, "Sending funding_locked WITHOUT announcement_signatures for {}", log_bytes!(channel.channel_id()));
3364                                                 }
3365                                                 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
3366                                         }
3367                                 } else if let Err(e) = res {
3368                                         if let Some(short_id) = channel.get_short_channel_id() {
3369                                                 short_to_id.remove(&short_id);
3370                                         }
3371                                         // It looks like our counterparty went on-chain or funding transaction was
3372                                         // reorged out of the main chain. Close the channel.
3373                                         failed_channels.push(channel.force_shutdown(true));
3374                                         if let Ok(update) = self.get_channel_update(&channel) {
3375                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3376                                                         msg: update
3377                                                 });
3378                                         }
3379                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
3380                                                 node_id: channel.get_counterparty_node_id(),
3381                                                 action: msgs::ErrorAction::SendErrorMessage { msg: e },
3382                                         });
3383                                         return false;
3384                                 }
3385                                 true
3386                         });
3387
3388                         channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3389                                 htlcs.retain(|htlc| {
3390                                         // If height is approaching the number of blocks we think it takes us to get
3391                                         // our commitment transaction confirmed before the HTLC expires, plus the
3392                                         // number of blocks we generally consider it to take to do a commitment update,
3393                                         // just give up on it and fail the HTLC.
3394                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3395                                                 let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3396                                                 htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3397                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3398                                                         failure_code: 0x4000 | 15,
3399                                                         data: htlc_msat_height_data
3400                                                 }));
3401                                                 false
3402                                         } else { true }
3403                                 });
3404                                 !htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3405                         });
3406                 }
3407
3408                 self.handle_init_event_channel_failures(failed_channels);
3409
3410                 for (source, payment_hash, reason) in timed_out_htlcs.drain(..) {
3411                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), source, &payment_hash, reason);
3412                 }
3413         }
3414
3415         /// Updates channel state to take note of transactions which were confirmed in the given block
3416         /// at the given height.
3417         ///
3418         /// Note that you must still call (or have called) [`update_best_block`] with the block
3419         /// information which is included here.
3420         ///
3421         /// This method may be called before or after [`update_best_block`] for a given block's
3422         /// transaction data and may be called multiple times with additional transaction data for a
3423         /// given block.
3424         ///
3425         /// This method may be called for a previous block after an [`update_best_block`] call has
3426         /// been made for a later block, however it must *not* be called with transaction data from a
3427         /// block which is no longer in the best chain (ie where [`update_best_block`] has already
3428         /// been informed about a blockchain reorganization which no longer includes the block which
3429         /// corresponds to `header`).
3430         ///
3431         /// [`update_best_block`]: `Self::update_best_block`
3432         pub fn transactions_confirmed(&self, header: &BlockHeader, height: u32, txdata: &TransactionData) {
3433                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3434                 // during initialization prior to the chain_monitor being fully configured in some cases.
3435                 // See the docs for `ChannelManagerReadArgs` for more.
3436
3437                 let block_hash = header.block_hash();
3438                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
3439
3440                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3441                 self.do_chain_event(height, |channel| channel.transactions_confirmed(&block_hash, height, txdata, &self.logger).map(|a| (a, Vec::new())));
3442         }
3443
3444         /// Updates channel state with the current best blockchain tip. You should attempt to call this
3445         /// quickly after a new block becomes available, however if multiple new blocks become
3446         /// available at the same time, only a single `update_best_block()` call needs to be made.
3447         ///
3448         /// This method should also be called immediately after any block disconnections, once at the
3449         /// reorganization fork point, and once with the new chain tip. Calling this method at the
3450         /// blockchain reorganization fork point ensures we learn when a funding transaction which was
3451         /// previously confirmed is reorganized out of the blockchain, ensuring we do not continue to
3452         /// accept payments which cannot be enforced on-chain.
3453         ///
3454         /// In both the block-connection and block-disconnection case, this method may be called either
3455         /// once per block connected or disconnected, or simply at the fork point and new tip(s),
3456         /// skipping any intermediary blocks.
3457         pub fn update_best_block(&self, header: &BlockHeader, height: u32) {
3458                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
3459                 // during initialization prior to the chain_monitor being fully configured in some cases.
3460                 // See the docs for `ChannelManagerReadArgs` for more.
3461
3462                 let block_hash = header.block_hash();
3463                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
3464
3465                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3466
3467                 self.latest_block_height.store(height as usize, Ordering::Release);
3468                 *self.last_block_hash.write().unwrap() = block_hash;
3469
3470                 self.do_chain_event(height, |channel| channel.update_best_block(height, header.time));
3471
3472                 loop {
3473                         // Update last_node_announcement_serial to be the max of its current value and the
3474                         // block timestamp. This should keep us close to the current time without relying on
3475                         // having an explicit local time source.
3476                         // Just in case we end up in a race, we loop until we either successfully update
3477                         // last_node_announcement_serial or decide we don't need to.
3478                         let old_serial = self.last_node_announcement_serial.load(Ordering::Acquire);
3479                         if old_serial >= header.time as usize { break; }
3480                         if self.last_node_announcement_serial.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
3481                                 break;
3482                         }
3483                 }
3484         }
3485
3486         /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
3487         /// indicating whether persistence is necessary. Only one listener on
3488         /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3489         /// up.
3490         /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
3491         #[cfg(any(test, feature = "allow_wallclock_use"))]
3492         pub fn await_persistable_update_timeout(&self, max_wait: Duration) -> bool {
3493                 self.persistence_notifier.wait_timeout(max_wait)
3494         }
3495
3496         /// Blocks until ChannelManager needs to be persisted. Only one listener on
3497         /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
3498         /// up.
3499         pub fn await_persistable_update(&self) {
3500                 self.persistence_notifier.wait()
3501         }
3502
3503         #[cfg(any(test, feature = "_test_utils"))]
3504         pub fn get_persistence_condvar_value(&self) -> bool {
3505                 let mutcond = &self.persistence_notifier.persistence_lock;
3506                 let &(ref mtx, _) = mutcond;
3507                 let guard = mtx.lock().unwrap();
3508                 *guard
3509         }
3510 }
3511
3512 impl<Signer: Sign, M: Deref + Sync + Send, T: Deref + Sync + Send, K: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send>
3513         ChannelMessageHandler for ChannelManager<Signer, M, T, K, F, L>
3514         where M::Target: chain::Watch<Signer>,
3515         T::Target: BroadcasterInterface,
3516         K::Target: KeysInterface<Signer = Signer>,
3517         F::Target: FeeEstimator,
3518         L::Target: Logger,
3519 {
3520         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::OpenChannel) {
3521                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3522                 let _ = handle_error!(self, self.internal_open_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3523         }
3524
3525         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, their_features: InitFeatures, msg: &msgs::AcceptChannel) {
3526                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3527                 let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, their_features, msg), *counterparty_node_id);
3528         }
3529
3530         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
3531                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3532                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
3533         }
3534
3535         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
3536                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3537                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
3538         }
3539
3540         fn handle_funding_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingLocked) {
3541                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3542                 let _ = handle_error!(self, self.internal_funding_locked(counterparty_node_id, msg), *counterparty_node_id);
3543         }
3544
3545         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, their_features: &InitFeatures, msg: &msgs::Shutdown) {
3546                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3547                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, their_features, msg), *counterparty_node_id);
3548         }
3549
3550         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
3551                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3552                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
3553         }
3554
3555         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
3556                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3557                 let _ = handle_error!(self, self.internal_update_add_htlc(counterparty_node_id, msg), *counterparty_node_id);
3558         }
3559
3560         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
3561                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3562                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
3563         }
3564
3565         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
3566                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3567                 let _ = handle_error!(self, self.internal_update_fail_htlc(counterparty_node_id, msg), *counterparty_node_id);
3568         }
3569
3570         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
3571                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3572                 let _ = handle_error!(self, self.internal_update_fail_malformed_htlc(counterparty_node_id, msg), *counterparty_node_id);
3573         }
3574
3575         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
3576                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3577                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
3578         }
3579
3580         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
3581                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3582                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
3583         }
3584
3585         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
3586                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3587                 let _ = handle_error!(self, self.internal_update_fee(counterparty_node_id, msg), *counterparty_node_id);
3588         }
3589
3590         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
3591                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3592                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
3593         }
3594
3595         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
3596                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3597                 let _ = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id);
3598         }
3599
3600         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
3601                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3602                 let _ = handle_error!(self, self.internal_channel_reestablish(counterparty_node_id, msg), *counterparty_node_id);
3603         }
3604
3605         fn peer_disconnected(&self, counterparty_node_id: &PublicKey, no_connection_possible: bool) {
3606                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3607                 let mut failed_channels = Vec::new();
3608                 let mut failed_payments = Vec::new();
3609                 let mut no_channels_remain = true;
3610                 {
3611                         let mut channel_state_lock = self.channel_state.lock().unwrap();
3612                         let channel_state = &mut *channel_state_lock;
3613                         let short_to_id = &mut channel_state.short_to_id;
3614                         let pending_msg_events = &mut channel_state.pending_msg_events;
3615                         if no_connection_possible {
3616                                 log_debug!(self.logger, "Failing all channels with {} due to no_connection_possible", log_pubkey!(counterparty_node_id));
3617                                 channel_state.by_id.retain(|_, chan| {
3618                                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3619                                                 if let Some(short_id) = chan.get_short_channel_id() {
3620                                                         short_to_id.remove(&short_id);
3621                                                 }
3622                                                 failed_channels.push(chan.force_shutdown(true));
3623                                                 if let Ok(update) = self.get_channel_update(&chan) {
3624                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3625                                                                 msg: update
3626                                                         });
3627                                                 }
3628                                                 false
3629                                         } else {
3630                                                 true
3631                                         }
3632                                 });
3633                         } else {
3634                                 log_debug!(self.logger, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(counterparty_node_id));
3635                                 channel_state.by_id.retain(|_, chan| {
3636                                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3637                                                 // Note that currently on channel reestablish we assert that there are no
3638                                                 // holding cell add-HTLCs, so if in the future we stop removing uncommitted HTLCs
3639                                                 // on peer disconnect here, there will need to be corresponding changes in
3640                                                 // reestablish logic.
3641                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused(&self.logger);
3642                                                 chan.to_disabled_marked();
3643                                                 if !failed_adds.is_empty() {
3644                                                         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
3645                                                         failed_payments.push((chan_update, failed_adds));
3646                                                 }
3647                                                 if chan.is_shutdown() {
3648                                                         if let Some(short_id) = chan.get_short_channel_id() {
3649                                                                 short_to_id.remove(&short_id);
3650                                                         }
3651                                                         return false;
3652                                                 } else {
3653                                                         no_channels_remain = false;
3654                                                 }
3655                                         }
3656                                         true
3657                                 })
3658                         }
3659                         pending_msg_events.retain(|msg| {
3660                                 match msg {
3661                                         &events::MessageSendEvent::SendAcceptChannel { ref node_id, .. } => node_id != counterparty_node_id,
3662                                         &events::MessageSendEvent::SendOpenChannel { ref node_id, .. } => node_id != counterparty_node_id,
3663                                         &events::MessageSendEvent::SendFundingCreated { ref node_id, .. } => node_id != counterparty_node_id,
3664                                         &events::MessageSendEvent::SendFundingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3665                                         &events::MessageSendEvent::SendFundingLocked { ref node_id, .. } => node_id != counterparty_node_id,
3666                                         &events::MessageSendEvent::SendAnnouncementSignatures { ref node_id, .. } => node_id != counterparty_node_id,
3667                                         &events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => node_id != counterparty_node_id,
3668                                         &events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => node_id != counterparty_node_id,
3669                                         &events::MessageSendEvent::SendClosingSigned { ref node_id, .. } => node_id != counterparty_node_id,
3670                                         &events::MessageSendEvent::SendShutdown { ref node_id, .. } => node_id != counterparty_node_id,
3671                                         &events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => node_id != counterparty_node_id,
3672                                         &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
3673                                         &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
3674                                         &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
3675                                         &events::MessageSendEvent::HandleError { ref node_id, .. } => node_id != counterparty_node_id,
3676                                         &events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => true,
3677                                         &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
3678                                         &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
3679                                         &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
3680                                 }
3681                         });
3682                 }
3683                 if no_channels_remain {
3684                         self.per_peer_state.write().unwrap().remove(counterparty_node_id);
3685                 }
3686
3687                 for failure in failed_channels.drain(..) {
3688                         self.finish_force_close_channel(failure);
3689                 }
3690                 for (chan_update, mut htlc_sources) in failed_payments {
3691                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
3692                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
3693                         }
3694                 }
3695         }
3696
3697         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init) {
3698                 log_debug!(self.logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
3699
3700                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3701
3702                 {
3703                         let mut peer_state_lock = self.per_peer_state.write().unwrap();
3704                         match peer_state_lock.entry(counterparty_node_id.clone()) {
3705                                 hash_map::Entry::Vacant(e) => {
3706                                         e.insert(Mutex::new(PeerState {
3707                                                 latest_features: init_msg.features.clone(),
3708                                         }));
3709                                 },
3710                                 hash_map::Entry::Occupied(e) => {
3711                                         e.get().lock().unwrap().latest_features = init_msg.features.clone();
3712                                 },
3713                         }
3714                 }
3715
3716                 let mut channel_state_lock = self.channel_state.lock().unwrap();
3717                 let channel_state = &mut *channel_state_lock;
3718                 let pending_msg_events = &mut channel_state.pending_msg_events;
3719                 channel_state.by_id.retain(|_, chan| {
3720                         if chan.get_counterparty_node_id() == *counterparty_node_id {
3721                                 if !chan.have_received_message() {
3722                                         // If we created this (outbound) channel while we were disconnected from the
3723                                         // peer we probably failed to send the open_channel message, which is now
3724                                         // lost. We can't have had anything pending related to this channel, so we just
3725                                         // drop it.
3726                                         false
3727                                 } else {
3728                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
3729                                                 node_id: chan.get_counterparty_node_id(),
3730                                                 msg: chan.get_channel_reestablish(&self.logger),
3731                                         });
3732                                         true
3733                                 }
3734                         } else { true }
3735                 });
3736                 //TODO: Also re-broadcast announcement_signatures
3737         }
3738
3739         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
3740                 let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3741
3742                 if msg.channel_id == [0; 32] {
3743                         for chan in self.list_channels() {
3744                                 if chan.remote_network_id == *counterparty_node_id {
3745                                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3746                                         let _ = self.force_close_channel_with_peer(&chan.channel_id, Some(counterparty_node_id));
3747                                 }
3748                         }
3749                 } else {
3750                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
3751                         let _ = self.force_close_channel_with_peer(&msg.channel_id, Some(counterparty_node_id));
3752                 }
3753         }
3754 }
3755
3756 /// Used to signal to the ChannelManager persister that the manager needs to be re-persisted to
3757 /// disk/backups, through `await_persistable_update_timeout` and `await_persistable_update`.
3758 struct PersistenceNotifier {
3759         /// Users won't access the persistence_lock directly, but rather wait on its bool using
3760         /// `wait_timeout` and `wait`.
3761         persistence_lock: (Mutex<bool>, Condvar),
3762 }
3763
3764 impl PersistenceNotifier {
3765         fn new() -> Self {
3766                 Self {
3767                         persistence_lock: (Mutex::new(false), Condvar::new()),
3768                 }
3769         }
3770
3771         fn wait(&self) {
3772                 loop {
3773                         let &(ref mtx, ref cvar) = &self.persistence_lock;
3774                         let mut guard = mtx.lock().unwrap();
3775                         guard = cvar.wait(guard).unwrap();
3776                         let result = *guard;
3777                         if result {
3778                                 *guard = false;
3779                                 return
3780                         }
3781                 }
3782         }
3783
3784         #[cfg(any(test, feature = "allow_wallclock_use"))]
3785         fn wait_timeout(&self, max_wait: Duration) -> bool {
3786                 let current_time = Instant::now();
3787                 loop {
3788                         let &(ref mtx, ref cvar) = &self.persistence_lock;
3789                         let mut guard = mtx.lock().unwrap();
3790                         guard = cvar.wait_timeout(guard, max_wait).unwrap().0;
3791                         // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
3792                         // desired wait time has actually passed, and if not then restart the loop with a reduced wait
3793                         // time. Note that this logic can be highly simplified through the use of
3794                         // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
3795                         // 1.42.0.
3796                         let elapsed = current_time.elapsed();
3797                         let result = *guard;
3798                         if result || elapsed >= max_wait {
3799                                 *guard = false;
3800                                 return result;
3801                         }
3802                         match max_wait.checked_sub(elapsed) {
3803                                 None => return result,
3804                                 Some(_) => continue
3805                         }
3806                 }
3807         }
3808
3809         // Signal to the ChannelManager persister that there are updates necessitating persisting to disk.
3810         fn notify(&self) {
3811                 let &(ref persist_mtx, ref cnd) = &self.persistence_lock;
3812                 let mut persistence_lock = persist_mtx.lock().unwrap();
3813                 *persistence_lock = true;
3814                 mem::drop(persistence_lock);
3815                 cnd.notify_all();
3816         }
3817 }
3818
3819 const SERIALIZATION_VERSION: u8 = 1;
3820 const MIN_SERIALIZATION_VERSION: u8 = 1;
3821
3822 impl Writeable for PendingHTLCInfo {
3823         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3824                 match &self.routing {
3825                         &PendingHTLCRouting::Forward { ref onion_packet, ref short_channel_id } => {
3826                                 0u8.write(writer)?;
3827                                 onion_packet.write(writer)?;
3828                                 short_channel_id.write(writer)?;
3829                         },
3830                         &PendingHTLCRouting::Receive { ref payment_data, ref incoming_cltv_expiry } => {
3831                                 1u8.write(writer)?;
3832                                 payment_data.write(writer)?;
3833                                 incoming_cltv_expiry.write(writer)?;
3834                         },
3835                 }
3836                 self.incoming_shared_secret.write(writer)?;
3837                 self.payment_hash.write(writer)?;
3838                 self.amt_to_forward.write(writer)?;
3839                 self.outgoing_cltv_value.write(writer)?;
3840                 Ok(())
3841         }
3842 }
3843
3844 impl Readable for PendingHTLCInfo {
3845         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCInfo, DecodeError> {
3846                 Ok(PendingHTLCInfo {
3847                         routing: match Readable::read(reader)? {
3848                                 0u8 => PendingHTLCRouting::Forward {
3849                                         onion_packet: Readable::read(reader)?,
3850                                         short_channel_id: Readable::read(reader)?,
3851                                 },
3852                                 1u8 => PendingHTLCRouting::Receive {
3853                                         payment_data: Readable::read(reader)?,
3854                                         incoming_cltv_expiry: Readable::read(reader)?,
3855                                 },
3856                                 _ => return Err(DecodeError::InvalidValue),
3857                         },
3858                         incoming_shared_secret: Readable::read(reader)?,
3859                         payment_hash: Readable::read(reader)?,
3860                         amt_to_forward: Readable::read(reader)?,
3861                         outgoing_cltv_value: Readable::read(reader)?,
3862                 })
3863         }
3864 }
3865
3866 impl Writeable for HTLCFailureMsg {
3867         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3868                 match self {
3869                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3870                                 0u8.write(writer)?;
3871                                 fail_msg.write(writer)?;
3872                         },
3873                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3874                                 1u8.write(writer)?;
3875                                 fail_msg.write(writer)?;
3876                         }
3877                 }
3878                 Ok(())
3879         }
3880 }
3881
3882 impl Readable for HTLCFailureMsg {
3883         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3884                 match <u8 as Readable>::read(reader)? {
3885                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3886                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3887                         _ => Err(DecodeError::InvalidValue),
3888                 }
3889         }
3890 }
3891
3892 impl Writeable for PendingHTLCStatus {
3893         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3894                 match self {
3895                         &PendingHTLCStatus::Forward(ref forward_info) => {
3896                                 0u8.write(writer)?;
3897                                 forward_info.write(writer)?;
3898                         },
3899                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3900                                 1u8.write(writer)?;
3901                                 fail_msg.write(writer)?;
3902                         }
3903                 }
3904                 Ok(())
3905         }
3906 }
3907
3908 impl Readable for PendingHTLCStatus {
3909         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3910                 match <u8 as Readable>::read(reader)? {
3911                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3912                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3913                         _ => Err(DecodeError::InvalidValue),
3914                 }
3915         }
3916 }
3917
3918 impl_writeable!(HTLCPreviousHopData, 0, {
3919         short_channel_id,
3920         outpoint,
3921         htlc_id,
3922         incoming_packet_shared_secret
3923 });
3924
3925 impl_writeable!(ClaimableHTLC, 0, {
3926         prev_hop,
3927         value,
3928         payment_data,
3929         cltv_expiry
3930 });
3931
3932 impl Writeable for HTLCSource {
3933         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3934                 match self {
3935                         &HTLCSource::PreviousHopData(ref hop_data) => {
3936                                 0u8.write(writer)?;
3937                                 hop_data.write(writer)?;
3938                         },
3939                         &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } => {
3940                                 1u8.write(writer)?;
3941                                 path.write(writer)?;
3942                                 session_priv.write(writer)?;
3943                                 first_hop_htlc_msat.write(writer)?;
3944                         }
3945                 }
3946                 Ok(())
3947         }
3948 }
3949
3950 impl Readable for HTLCSource {
3951         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3952                 match <u8 as Readable>::read(reader)? {
3953                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3954                         1 => Ok(HTLCSource::OutboundRoute {
3955                                 path: Readable::read(reader)?,
3956                                 session_priv: Readable::read(reader)?,
3957                                 first_hop_htlc_msat: Readable::read(reader)?,
3958                         }),
3959                         _ => Err(DecodeError::InvalidValue),
3960                 }
3961         }
3962 }
3963
3964 impl Writeable for HTLCFailReason {
3965         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3966                 match self {
3967                         &HTLCFailReason::LightningError { ref err } => {
3968                                 0u8.write(writer)?;
3969                                 err.write(writer)?;
3970                         },
3971                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3972                                 1u8.write(writer)?;
3973                                 failure_code.write(writer)?;
3974                                 data.write(writer)?;
3975                         }
3976                 }
3977                 Ok(())
3978         }
3979 }
3980
3981 impl Readable for HTLCFailReason {
3982         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3983                 match <u8 as Readable>::read(reader)? {
3984                         0 => Ok(HTLCFailReason::LightningError { err: Readable::read(reader)? }),
3985                         1 => Ok(HTLCFailReason::Reason {
3986                                 failure_code: Readable::read(reader)?,
3987                                 data: Readable::read(reader)?,
3988                         }),
3989                         _ => Err(DecodeError::InvalidValue),
3990                 }
3991         }
3992 }
3993
3994 impl Writeable for HTLCForwardInfo {
3995         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3996                 match self {
3997                         &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_funding_outpoint, ref prev_htlc_id, ref forward_info } => {
3998                                 0u8.write(writer)?;
3999                                 prev_short_channel_id.write(writer)?;
4000                                 prev_funding_outpoint.write(writer)?;
4001                                 prev_htlc_id.write(writer)?;
4002                                 forward_info.write(writer)?;
4003                         },
4004                         &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
4005                                 1u8.write(writer)?;
4006                                 htlc_id.write(writer)?;
4007                                 err_packet.write(writer)?;
4008                         },
4009                 }
4010                 Ok(())
4011         }
4012 }
4013
4014 impl Readable for HTLCForwardInfo {
4015         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
4016                 match <u8 as Readable>::read(reader)? {
4017                         0 => Ok(HTLCForwardInfo::AddHTLC {
4018                                 prev_short_channel_id: Readable::read(reader)?,
4019                                 prev_funding_outpoint: Readable::read(reader)?,
4020                                 prev_htlc_id: Readable::read(reader)?,
4021                                 forward_info: Readable::read(reader)?,
4022                         }),
4023                         1 => Ok(HTLCForwardInfo::FailHTLC {
4024                                 htlc_id: Readable::read(reader)?,
4025                                 err_packet: Readable::read(reader)?,
4026                         }),
4027                         _ => Err(DecodeError::InvalidValue),
4028                 }
4029         }
4030 }
4031
4032 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelManager<Signer, M, T, K, F, L>
4033         where M::Target: chain::Watch<Signer>,
4034         T::Target: BroadcasterInterface,
4035         K::Target: KeysInterface<Signer = Signer>,
4036         F::Target: FeeEstimator,
4037         L::Target: Logger,
4038 {
4039         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
4040                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
4041
4042                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
4043                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
4044
4045                 self.genesis_hash.write(writer)?;
4046                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
4047                 self.last_block_hash.read().unwrap().write(writer)?;
4048
4049                 let channel_state = self.channel_state.lock().unwrap();
4050                 let mut unfunded_channels = 0;
4051                 for (_, channel) in channel_state.by_id.iter() {
4052                         if !channel.is_funding_initiated() {
4053                                 unfunded_channels += 1;
4054                         }
4055                 }
4056                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
4057                 for (_, channel) in channel_state.by_id.iter() {
4058                         if channel.is_funding_initiated() {
4059                                 channel.write(writer)?;
4060                         }
4061                 }
4062
4063                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
4064                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
4065                         short_channel_id.write(writer)?;
4066                         (pending_forwards.len() as u64).write(writer)?;
4067                         for forward in pending_forwards {
4068                                 forward.write(writer)?;
4069                         }
4070                 }
4071
4072                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
4073                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
4074                         payment_hash.write(writer)?;
4075                         (previous_hops.len() as u64).write(writer)?;
4076                         for htlc in previous_hops.iter() {
4077                                 htlc.write(writer)?;
4078                         }
4079                 }
4080
4081                 let per_peer_state = self.per_peer_state.write().unwrap();
4082                 (per_peer_state.len() as u64).write(writer)?;
4083                 for (peer_pubkey, peer_state_mutex) in per_peer_state.iter() {
4084                         peer_pubkey.write(writer)?;
4085                         let peer_state = peer_state_mutex.lock().unwrap();
4086                         peer_state.latest_features.write(writer)?;
4087                 }
4088
4089                 let events = self.pending_events.lock().unwrap();
4090                 (events.len() as u64).write(writer)?;
4091                 for event in events.iter() {
4092                         event.write(writer)?;
4093                 }
4094
4095                 let background_events = self.pending_background_events.lock().unwrap();
4096                 (background_events.len() as u64).write(writer)?;
4097                 for event in background_events.iter() {
4098                         match event {
4099                                 BackgroundEvent::ClosingMonitorUpdate((funding_txo, monitor_update)) => {
4100                                         0u8.write(writer)?;
4101                                         funding_txo.write(writer)?;
4102                                         monitor_update.write(writer)?;
4103                                 },
4104                         }
4105                 }
4106
4107                 (self.last_node_announcement_serial.load(Ordering::Acquire) as u32).write(writer)?;
4108
4109                 Ok(())
4110         }
4111 }
4112
4113 /// Arguments for the creation of a ChannelManager that are not deserialized.
4114 ///
4115 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
4116 /// is:
4117 /// 1) Deserialize all stored ChannelMonitors.
4118 /// 2) Deserialize the ChannelManager by filling in this struct and calling:
4119 ///    <(BlockHash, ChannelManager)>::read(reader, args)
4120 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
4121 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
4122 /// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same
4123 ///    way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and
4124 ///    ChannelMonitor::get_funding_txo().
4125 /// 4) Reconnect blocks on your ChannelMonitors.
4126 /// 5) Disconnect/connect blocks on the ChannelManager.
4127 /// 6) Move the ChannelMonitors into your local chain::Watch.
4128 ///
4129 /// Note that the ordering of #4-6 is not of importance, however all three must occur before you
4130 /// call any other methods on the newly-deserialized ChannelManager.
4131 ///
4132 /// Note that because some channels may be closed during deserialization, it is critical that you
4133 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
4134 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
4135 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
4136 /// not force-close the same channels but consider them live), you may end up revoking a state for
4137 /// which you've already broadcasted the transaction.
4138 pub struct ChannelManagerReadArgs<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4139         where M::Target: chain::Watch<Signer>,
4140         T::Target: BroadcasterInterface,
4141         K::Target: KeysInterface<Signer = Signer>,
4142         F::Target: FeeEstimator,
4143         L::Target: Logger,
4144 {
4145         /// The keys provider which will give us relevant keys. Some keys will be loaded during
4146         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
4147         /// signing data.
4148         pub keys_manager: K,
4149
4150         /// The fee_estimator for use in the ChannelManager in the future.
4151         ///
4152         /// No calls to the FeeEstimator will be made during deserialization.
4153         pub fee_estimator: F,
4154         /// The chain::Watch for use in the ChannelManager in the future.
4155         ///
4156         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
4157         /// you have deserialized ChannelMonitors separately and will add them to your
4158         /// chain::Watch after deserializing this ChannelManager.
4159         pub chain_monitor: M,
4160
4161         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
4162         /// used to broadcast the latest local commitment transactions of channels which must be
4163         /// force-closed during deserialization.
4164         pub tx_broadcaster: T,
4165         /// The Logger for use in the ChannelManager and which may be used to log information during
4166         /// deserialization.
4167         pub logger: L,
4168         /// Default settings used for new channels. Any existing channels will continue to use the
4169         /// runtime settings which were stored when the ChannelManager was serialized.
4170         pub default_config: UserConfig,
4171
4172         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
4173         /// value.get_funding_txo() should be the key).
4174         ///
4175         /// If a monitor is inconsistent with the channel state during deserialization the channel will
4176         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
4177         /// is true for missing channels as well. If there is a monitor missing for which we find
4178         /// channel data Err(DecodeError::InvalidValue) will be returned.
4179         ///
4180         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
4181         /// this struct.
4182         ///
4183         /// (C-not exported) because we have no HashMap bindings
4184         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<Signer>>,
4185 }
4186
4187 impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4188                 ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>
4189         where M::Target: chain::Watch<Signer>,
4190                 T::Target: BroadcasterInterface,
4191                 K::Target: KeysInterface<Signer = Signer>,
4192                 F::Target: FeeEstimator,
4193                 L::Target: Logger,
4194         {
4195         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
4196         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
4197         /// populate a HashMap directly from C.
4198         pub fn new(keys_manager: K, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, logger: L, default_config: UserConfig,
4199                         mut channel_monitors: Vec<&'a mut ChannelMonitor<Signer>>) -> Self {
4200                 Self {
4201                         keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, default_config,
4202                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
4203                 }
4204         }
4205 }
4206
4207 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
4208 // SipmleArcChannelManager type:
4209 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4210         ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
4211         where M::Target: chain::Watch<Signer>,
4212         T::Target: BroadcasterInterface,
4213         K::Target: KeysInterface<Signer = Signer>,
4214         F::Target: FeeEstimator,
4215         L::Target: Logger,
4216 {
4217         fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4218                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
4219                 Ok((blockhash, Arc::new(chan_manager)))
4220         }
4221 }
4222
4223 impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4224         ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
4225         where M::Target: chain::Watch<Signer>,
4226         T::Target: BroadcasterInterface,
4227         K::Target: KeysInterface<Signer = Signer>,
4228         F::Target: FeeEstimator,
4229         L::Target: Logger,
4230 {
4231         fn read<R: ::std::io::Read>(reader: &mut R, mut args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4232                 let _ver: u8 = Readable::read(reader)?;
4233                 let min_ver: u8 = Readable::read(reader)?;
4234                 if min_ver > SERIALIZATION_VERSION {
4235                         return Err(DecodeError::UnknownVersion);
4236                 }
4237
4238                 let genesis_hash: BlockHash = Readable::read(reader)?;
4239                 let latest_block_height: u32 = Readable::read(reader)?;
4240                 let last_block_hash: BlockHash = Readable::read(reader)?;
4241
4242                 let mut failed_htlcs = Vec::new();
4243
4244                 let channel_count: u64 = Readable::read(reader)?;
4245                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
4246                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4247                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
4248                 for _ in 0..channel_count {
4249                         let mut channel: Channel<Signer> = Channel::read(reader, &args.keys_manager)?;
4250                         let funding_txo = channel.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
4251                         funding_txo_set.insert(funding_txo.clone());
4252                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
4253                                 if channel.get_cur_holder_commitment_transaction_number() < monitor.get_cur_holder_commitment_number() ||
4254                                                 channel.get_revoked_counterparty_commitment_transaction_number() < monitor.get_min_seen_secret() ||
4255                                                 channel.get_cur_counterparty_commitment_transaction_number() < monitor.get_cur_counterparty_commitment_number() ||
4256                                                 channel.get_latest_monitor_update_id() > monitor.get_latest_update_id() {
4257                                         // If the channel is ahead of the monitor, return InvalidValue:
4258                                         return Err(DecodeError::InvalidValue);
4259                                 } else if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
4260                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
4261                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
4262                                                 channel.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
4263                                         // But if the channel is behind of the monitor, close the channel:
4264                                         let (_, mut new_failed_htlcs) = channel.force_shutdown(true);
4265                                         failed_htlcs.append(&mut new_failed_htlcs);
4266                                         monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4267                                 } else {
4268                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
4269                                                 short_to_id.insert(short_channel_id, channel.channel_id());
4270                                         }
4271                                         by_id.insert(channel.channel_id(), channel);
4272                                 }
4273                         } else {
4274                                 return Err(DecodeError::InvalidValue);
4275                         }
4276                 }
4277
4278                 for (ref funding_txo, ref mut monitor) in args.channel_monitors.iter_mut() {
4279                         if !funding_txo_set.contains(funding_txo) {
4280                                 monitor.broadcast_latest_holder_commitment_txn(&args.tx_broadcaster, &args.logger);
4281                         }
4282                 }
4283
4284                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
4285                 let forward_htlcs_count: u64 = Readable::read(reader)?;
4286                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
4287                 for _ in 0..forward_htlcs_count {
4288                         let short_channel_id = Readable::read(reader)?;
4289                         let pending_forwards_count: u64 = Readable::read(reader)?;
4290                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
4291                         for _ in 0..pending_forwards_count {
4292                                 pending_forwards.push(Readable::read(reader)?);
4293                         }
4294                         forward_htlcs.insert(short_channel_id, pending_forwards);
4295                 }
4296
4297                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
4298                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
4299                 for _ in 0..claimable_htlcs_count {
4300                         let payment_hash = Readable::read(reader)?;
4301                         let previous_hops_len: u64 = Readable::read(reader)?;
4302                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
4303                         for _ in 0..previous_hops_len {
4304                                 previous_hops.push(Readable::read(reader)?);
4305                         }
4306                         claimable_htlcs.insert(payment_hash, previous_hops);
4307                 }
4308
4309                 let peer_count: u64 = Readable::read(reader)?;
4310                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState>)>()));
4311                 for _ in 0..peer_count {
4312                         let peer_pubkey = Readable::read(reader)?;
4313                         let peer_state = PeerState {
4314                                 latest_features: Readable::read(reader)?,
4315                         };
4316                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
4317                 }
4318
4319                 let event_count: u64 = Readable::read(reader)?;
4320                 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>()));
4321                 for _ in 0..event_count {
4322                         match MaybeReadable::read(reader)? {
4323                                 Some(event) => pending_events_read.push(event),
4324                                 None => continue,
4325                         }
4326                 }
4327
4328                 let background_event_count: u64 = Readable::read(reader)?;
4329                 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>()));
4330                 for _ in 0..background_event_count {
4331                         match <u8 as Readable>::read(reader)? {
4332                                 0 => pending_background_events_read.push(BackgroundEvent::ClosingMonitorUpdate((Readable::read(reader)?, Readable::read(reader)?))),
4333                                 _ => return Err(DecodeError::InvalidValue),
4334                         }
4335                 }
4336
4337                 let last_node_announcement_serial: u32 = Readable::read(reader)?;
4338
4339                 let mut secp_ctx = Secp256k1::new();
4340                 secp_ctx.seeded_randomize(&args.keys_manager.get_secure_random_bytes());
4341
4342                 let channel_manager = ChannelManager {
4343                         genesis_hash,
4344                         fee_estimator: args.fee_estimator,
4345                         chain_monitor: args.chain_monitor,
4346                         tx_broadcaster: args.tx_broadcaster,
4347
4348                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
4349                         last_block_hash: RwLock::new(last_block_hash),
4350
4351                         channel_state: Mutex::new(ChannelHolder {
4352                                 by_id,
4353                                 short_to_id,
4354                                 forward_htlcs,
4355                                 claimable_htlcs,
4356                                 pending_msg_events: Vec::new(),
4357                         }),
4358                         our_network_key: args.keys_manager.get_node_secret(),
4359                         our_network_pubkey: PublicKey::from_secret_key(&secp_ctx, &args.keys_manager.get_node_secret()),
4360                         secp_ctx,
4361
4362                         last_node_announcement_serial: AtomicUsize::new(last_node_announcement_serial as usize),
4363
4364                         per_peer_state: RwLock::new(per_peer_state),
4365
4366                         pending_events: Mutex::new(pending_events_read),
4367                         pending_background_events: Mutex::new(pending_background_events_read),
4368                         total_consistency_lock: RwLock::new(()),
4369                         persistence_notifier: PersistenceNotifier::new(),
4370
4371                         keys_manager: args.keys_manager,
4372                         logger: args.logger,
4373                         default_configuration: args.default_config,
4374                 };
4375
4376                 for htlc_source in failed_htlcs.drain(..) {
4377                         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() });
4378                 }
4379
4380                 //TODO: Broadcast channel update for closed channels, but only after we've made a
4381                 //connection or two.
4382
4383                 Ok((last_block_hash.clone(), channel_manager))
4384         }
4385 }
4386
4387 #[cfg(test)]
4388 mod tests {
4389         use ln::channelmanager::PersistenceNotifier;
4390         use std::sync::Arc;
4391         use std::sync::atomic::{AtomicBool, Ordering};
4392         use std::thread;
4393         use std::time::Duration;
4394
4395         #[test]
4396         fn test_wait_timeout() {
4397                 let persistence_notifier = Arc::new(PersistenceNotifier::new());
4398                 let thread_notifier = Arc::clone(&persistence_notifier);
4399
4400                 let exit_thread = Arc::new(AtomicBool::new(false));
4401                 let exit_thread_clone = exit_thread.clone();
4402                 thread::spawn(move || {
4403                         loop {
4404                                 let &(ref persist_mtx, ref cnd) = &thread_notifier.persistence_lock;
4405                                 let mut persistence_lock = persist_mtx.lock().unwrap();
4406                                 *persistence_lock = true;
4407                                 cnd.notify_all();
4408
4409                                 if exit_thread_clone.load(Ordering::SeqCst) {
4410                                         break
4411                                 }
4412                         }
4413                 });
4414
4415                 // Check that we can block indefinitely until updates are available.
4416                 let _ = persistence_notifier.wait();
4417
4418                 // Check that the PersistenceNotifier will return after the given duration if updates are
4419                 // available.
4420                 loop {
4421                         if persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4422                                 break
4423                         }
4424                 }
4425
4426                 exit_thread.store(true, Ordering::SeqCst);
4427
4428                 // Check that the PersistenceNotifier will return after the given duration even if no updates
4429                 // are available.
4430                 loop {
4431                         if !persistence_notifier.wait_timeout(Duration::from_millis(100)) {
4432                                 break
4433                         }
4434                 }
4435         }
4436 }
4437
4438 #[cfg(all(any(test, feature = "_test_utils"), feature = "unstable"))]
4439 pub mod bench {
4440         use chain::Listen;
4441         use chain::chainmonitor::ChainMonitor;
4442         use chain::channelmonitor::Persist;
4443         use chain::keysinterface::{KeysManager, InMemorySigner};
4444         use chain::transaction::OutPoint;
4445         use ln::channelmanager::{ChainParameters, ChannelManager, PaymentHash, PaymentPreimage};
4446         use ln::features::InitFeatures;
4447         use ln::functional_test_utils::*;
4448         use ln::msgs::ChannelMessageHandler;
4449         use routing::network_graph::NetworkGraph;
4450         use routing::router::get_route;
4451         use util::test_utils;
4452         use util::config::UserConfig;
4453         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
4454
4455         use bitcoin::hashes::Hash;
4456         use bitcoin::hashes::sha256::Hash as Sha256;
4457         use bitcoin::{Block, BlockHeader, Transaction, TxOut};
4458
4459         use std::sync::Mutex;
4460
4461         use test::Bencher;
4462
4463         struct NodeHolder<'a, P: Persist<InMemorySigner>> {
4464                 node: &'a ChannelManager<InMemorySigner,
4465                         &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
4466                                 &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
4467                                 &'a test_utils::TestLogger, &'a P>,
4468                         &'a test_utils::TestBroadcaster, &'a KeysManager,
4469                         &'a test_utils::TestFeeEstimator, &'a test_utils::TestLogger>
4470         }
4471
4472         #[cfg(test)]
4473         #[bench]
4474         fn bench_sends(bench: &mut Bencher) {
4475                 bench_two_sends(bench, test_utils::TestPersister::new(), test_utils::TestPersister::new());
4476         }
4477
4478         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Bencher, persister_a: P, persister_b: P) {
4479                 // Do a simple benchmark of sending a payment back and forth between two nodes.
4480                 // Note that this is unrealistic as each payment send will require at least two fsync
4481                 // calls per node.
4482                 let network = bitcoin::Network::Testnet;
4483                 let genesis_hash = bitcoin::blockdata::constants::genesis_block(network).header.block_hash();
4484
4485                 let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
4486                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4487
4488                 let mut config: UserConfig = Default::default();
4489                 config.own_channel_config.minimum_depth = 1;
4490
4491                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
4492                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
4493                 let seed_a = [1u8; 32];
4494                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
4495                 let node_a = ChannelManager::new(&fee_estimator, &chain_monitor_a, &tx_broadcaster, &logger_a, &keys_manager_a, config.clone(), ChainParameters {
4496                         network,
4497                         latest_hash: genesis_hash,
4498                         latest_height: 0,
4499                 });
4500                 let node_a_holder = NodeHolder { node: &node_a };
4501
4502                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
4503                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
4504                 let seed_b = [2u8; 32];
4505                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
4506                 let node_b = ChannelManager::new(&fee_estimator, &chain_monitor_b, &tx_broadcaster, &logger_b, &keys_manager_b, config.clone(), ChainParameters {
4507                         network,
4508                         latest_hash: genesis_hash,
4509                         latest_height: 0,
4510                 });
4511                 let node_b_holder = NodeHolder { node: &node_b };
4512
4513                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None).unwrap();
4514                 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()));
4515                 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()));
4516
4517                 let tx;
4518                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
4519                         tx = Transaction { version: 2, lock_time: 0, input: Vec::new(), output: vec![TxOut {
4520                                 value: 8_000_000, script_pubkey: output_script,
4521                         }]};
4522                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
4523                         node_a.funding_transaction_generated(&temporary_channel_id, funding_outpoint);
4524                 } else { panic!(); }
4525
4526                 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()));
4527                 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()));
4528
4529                 get_event!(node_a_holder, Event::FundingBroadcastSafe);
4530
4531                 let block = Block {
4532                         header: BlockHeader { version: 0x20000000, prev_blockhash: genesis_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4533                         txdata: vec![tx],
4534                 };
4535                 Listen::block_connected(&node_a, &block, 1);
4536                 Listen::block_connected(&node_b, &block, 1);
4537
4538                 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()));
4539                 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()));
4540
4541                 let dummy_graph = NetworkGraph::new(genesis_hash);
4542
4543                 macro_rules! send_payment {
4544                         ($node_a: expr, $node_b: expr) => {
4545                                 let usable_channels = $node_a.list_usable_channels();
4546                                 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();
4547
4548                                 let payment_preimage = PaymentPreimage([0; 32]);
4549                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
4550
4551                                 $node_a.send_payment(&route, payment_hash, &None).unwrap();
4552                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
4553                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
4554                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
4555                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_b }, $node_a.get_our_node_id());
4556                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
4557                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
4558                                 $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()));
4559
4560                                 expect_pending_htlcs_forwardable!(NodeHolder { node: &$node_b });
4561                                 expect_payment_received!(NodeHolder { node: &$node_b }, payment_hash, 10_000);
4562                                 assert!($node_b.claim_funds(payment_preimage, &None, 10_000));
4563
4564                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
4565                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
4566                                                 assert_eq!(node_id, $node_a.get_our_node_id());
4567                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4568                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
4569                                         },
4570                                         _ => panic!("Failed to generate claim event"),
4571                                 }
4572
4573                                 let (raa, cs) = get_revoke_commit_msgs!(NodeHolder { node: &$node_a }, $node_b.get_our_node_id());
4574                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
4575                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
4576                                 $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()));
4577
4578                                 expect_payment_sent!(NodeHolder { node: &$node_a }, payment_preimage);
4579                         }
4580                 }
4581
4582                 bench.iter(|| {
4583                         send_payment!(node_a, node_b);
4584                         send_payment!(node_b, node_a);
4585                 });
4586         }
4587 }