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