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