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