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