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