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