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