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