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