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