Add ChainWatchInterface in Router
[rust-lightning] / src / ln / channelmanager.rs
1 use bitcoin::blockdata::block::BlockHeader;
2 use bitcoin::blockdata::transaction::Transaction;
3 use bitcoin::blockdata::constants::genesis_block;
4 use bitcoin::network::constants::Network;
5 use bitcoin::network::serialize::BitcoinHash;
6 use bitcoin::util::hash::Sha256dHash;
7
8 use secp256k1::key::{SecretKey,PublicKey};
9 use secp256k1::{Secp256k1,Message};
10 use secp256k1::ecdh::SharedSecret;
11 use secp256k1;
12
13 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
14 use chain::transaction::OutPoint;
15 use ln::channel::{Channel, ChannelKeys};
16 use ln::channelmonitor::ManyChannelMonitor;
17 use ln::router::{Route,RouteHop};
18 use ln::msgs;
19 use ln::msgs::{HandleError,ChannelMessageHandler,MsgEncodable,MsgDecodable};
20 use util::{byte_utils, events, internal_traits, rng};
21 use util::sha2::Sha256;
22 use util::chacha20poly1305rfc::ChaCha20;
23 use util::logger::Logger;
24 use util::errors::APIError;
25
26 use crypto;
27 use crypto::mac::{Mac,MacResult};
28 use crypto::hmac::Hmac;
29 use crypto::digest::Digest;
30 use crypto::symmetriccipher::SynchronousStreamCipher;
31
32 use std::{ptr, mem};
33 use std::collections::HashMap;
34 use std::collections::hash_map;
35 use std::sync::{Mutex,MutexGuard,Arc};
36 use std::sync::atomic::{AtomicUsize, Ordering};
37 use std::time::{Instant,Duration};
38
39 mod channel_held_info {
40         use ln::msgs;
41
42         /// Stores the info we will need to send when we want to forward an HTLC onwards
43         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
44         pub struct PendingForwardHTLCInfo {
45                 pub(super) onion_packet: Option<msgs::OnionPacket>,
46                 pub(super) payment_hash: [u8; 32],
47                 pub(super) short_channel_id: u64,
48                 pub(super) prev_short_channel_id: u64,
49                 pub(super) amt_to_forward: u64,
50                 pub(super) outgoing_cltv_value: u32,
51         }
52
53         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
54         pub enum HTLCFailureMsg {
55                 Relay(msgs::UpdateFailHTLC),
56                 Malformed(msgs::UpdateFailMalformedHTLC),
57         }
58
59         /// Stores whether we can't forward an HTLC or relevant forwarding info
60         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
61         pub enum PendingHTLCStatus {
62                 Forward(PendingForwardHTLCInfo),
63                 Fail(HTLCFailureMsg),
64         }
65
66         #[cfg(feature = "fuzztarget")]
67         impl PendingHTLCStatus {
68                 pub fn dummy() -> Self {
69                         PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
70                                 onion_packet: None,
71                                 payment_hash: [0; 32],
72                                 short_channel_id: 0,
73                                 prev_short_channel_id: 0,
74                                 amt_to_forward: 0,
75                                 outgoing_cltv_value: 0,
76                         })
77                 }
78         }
79
80         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81         pub enum HTLCFailReason {
82                 ErrorPacket {
83                         err: msgs::OnionErrorPacket,
84                 },
85                 Reason {
86                         failure_code: u16,
87                         data: Vec<u8>,
88                 }
89         }
90
91         #[cfg(feature = "fuzztarget")]
92         impl HTLCFailReason {
93                 pub fn dummy() -> Self {
94                         HTLCFailReason::Reason {
95                                 failure_code: 0, data: Vec::new(),
96                         }
97                 }
98         }
99 }
100 #[cfg(feature = "fuzztarget")]
101 pub use self::channel_held_info::*;
102 #[cfg(not(feature = "fuzztarget"))]
103 pub(crate) use self::channel_held_info::*;
104
105 enum PendingOutboundHTLC {
106         IntermediaryHopData {
107                 source_short_channel_id: u64,
108                 incoming_packet_shared_secret: SharedSecret,
109         },
110         OutboundRoute {
111                 route: Route,
112                 session_priv: SecretKey,
113         },
114         /// Used for channel rebalancing
115         CycledRoute {
116                 source_short_channel_id: u64,
117                 incoming_packet_shared_secret: SharedSecret,
118                 route: Route,
119                 session_priv: SecretKey,
120         }
121 }
122
123 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
124 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
125 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
126 /// probably increase this significantly.
127 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
128
129 struct ChannelHolder {
130         by_id: HashMap<[u8; 32], Channel>,
131         short_to_id: HashMap<u64, [u8; 32]>,
132         next_forward: Instant,
133         /// short channel id -> forward infos. Key of 0 means payments received
134         /// Note that while this is held in the same mutex as the channels themselves, no consistency
135         /// guarantees are made about there existing a channel with the short id here, nor the short
136         /// ids in the PendingForwardHTLCInfo!
137         forward_htlcs: HashMap<u64, Vec<PendingForwardHTLCInfo>>,
138         /// Note that while this is held in the same mutex as the channels themselves, no consistency
139         /// guarantees are made about the channels given here actually existing anymore by the time you
140         /// go to read them!
141         claimable_htlcs: HashMap<[u8; 32], PendingOutboundHTLC>,
142 }
143 struct MutChannelHolder<'a> {
144         by_id: &'a mut HashMap<[u8; 32], Channel>,
145         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
146         next_forward: &'a mut Instant,
147         forward_htlcs: &'a mut HashMap<u64, Vec<PendingForwardHTLCInfo>>,
148         claimable_htlcs: &'a mut HashMap<[u8; 32], PendingOutboundHTLC>,
149 }
150 impl ChannelHolder {
151         fn borrow_parts(&mut self) -> MutChannelHolder {
152                 MutChannelHolder {
153                         by_id: &mut self.by_id,
154                         short_to_id: &mut self.short_to_id,
155                         next_forward: &mut self.next_forward,
156                         forward_htlcs: &mut self.forward_htlcs,
157                         claimable_htlcs: &mut self.claimable_htlcs,
158                 }
159         }
160 }
161
162 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
163 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
164
165 /// Manager which keeps track of a number of channels and sends messages to the appropriate
166 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
167 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
168 /// to individual Channels.
169 pub struct ChannelManager {
170         genesis_hash: Sha256dHash,
171         fee_estimator: Arc<FeeEstimator>,
172         monitor: Arc<ManyChannelMonitor>,
173         chain_monitor: Arc<ChainWatchInterface>,
174         tx_broadcaster: Arc<BroadcasterInterface>,
175
176         announce_channels_publicly: bool,
177         fee_proportional_millionths: u32,
178         latest_block_height: AtomicUsize,
179         secp_ctx: Secp256k1<secp256k1::All>,
180
181         channel_state: Mutex<ChannelHolder>,
182         our_network_key: SecretKey,
183
184         pending_events: Mutex<Vec<events::Event>>,
185
186         logger: Arc<Logger>,
187 }
188
189 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
190
191 macro_rules! secp_call {
192         ( $res : expr ) => {
193                 match $res {
194                         Ok(key) => key,
195                         //TODO: Make the err a parameter!
196                         Err(_) => return Err(HandleError{err: "Key error", action: None})
197                 }
198         };
199 }
200
201 struct OnionKeys {
202         #[cfg(test)]
203         shared_secret: SharedSecret,
204         #[cfg(test)]
205         blinding_factor: [u8; 32],
206         ephemeral_pubkey: PublicKey,
207         rho: [u8; 32],
208         mu: [u8; 32],
209 }
210
211 pub struct ChannelDetails {
212         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
213         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
214         /// Note that this means this value is *not* persistent - it can change once during the
215         /// lifetime of the channel.
216         pub channel_id: [u8; 32],
217         /// The position of the funding transaction in the chain. None if the funding transaction has
218         /// not yet been confirmed and the channel fully opened.
219         pub short_channel_id: Option<u64>,
220         pub remote_network_id: PublicKey,
221         pub channel_value_satoshis: u64,
222         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
223         pub user_id: u64,
224 }
225
226 impl ChannelManager {
227         /// Constructs a new ChannelManager to hold several channels and route between them. This is
228         /// the main "logic hub" for all channel-related actions, and implements ChannelMessageHandler.
229         /// fee_proportional_millionths is an optional fee to charge any payments routed through us.
230         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
231         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
232         pub fn new(our_network_key: SecretKey, fee_proportional_millionths: u32, announce_channels_publicly: bool, network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Result<Arc<ChannelManager>, secp256k1::Error> {
233                 let secp_ctx = Secp256k1::new();
234
235                 let res = Arc::new(ChannelManager {
236                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
237                         fee_estimator: feeest.clone(),
238                         monitor: monitor.clone(),
239                         chain_monitor,
240                         tx_broadcaster,
241
242                         announce_channels_publicly,
243                         fee_proportional_millionths,
244                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
245                         secp_ctx,
246
247                         channel_state: Mutex::new(ChannelHolder{
248                                 by_id: HashMap::new(),
249                                 short_to_id: HashMap::new(),
250                                 next_forward: Instant::now(),
251                                 forward_htlcs: HashMap::new(),
252                                 claimable_htlcs: HashMap::new(),
253                         }),
254                         our_network_key,
255
256                         pending_events: Mutex::new(Vec::new()),
257
258                         logger,
259                 });
260                 let weak_res = Arc::downgrade(&res);
261                 res.chain_monitor.register_listener(weak_res);
262                 Ok(res)
263         }
264
265         /// Creates a new outbound channel to the given remote node and with the given value.
266         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
267         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
268         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
269         /// may wish to avoid using 0 for user_id here.
270         /// If successful, will generate a SendOpenChannel event, so you should probably poll
271         /// PeerManager::process_events afterwards.
272         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat being greater than channel_value_satoshis * 1k
273         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
274                 let chan_keys = if cfg!(feature = "fuzztarget") {
275                         ChannelKeys {
276                                 funding_key:               SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
277                                 revocation_base_key:       SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
278                                 payment_base_key:          SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
279                                 delayed_payment_base_key:  SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
280                                 htlc_base_key:             SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
281                                 channel_close_key:         SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
282                                 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
283                                 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
284                         }
285                 } else {
286                         let mut key_seed = [0u8; 32];
287                         rng::fill_bytes(&mut key_seed);
288                         match ChannelKeys::new_from_seed(&key_seed) {
289                                 Ok(key) => key,
290                                 Err(_) => panic!("RNG is busted!")
291                         }
292                 };
293
294                 let channel = Channel::new_outbound(&*self.fee_estimator, chan_keys, their_network_key, channel_value_satoshis, push_msat, self.announce_channels_publicly, user_id, Arc::clone(&self.logger))?;
295                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator)?;
296                 let mut channel_state = self.channel_state.lock().unwrap();
297                 match channel_state.by_id.insert(channel.channel_id(), channel) {
298                         Some(_) => panic!("RNG is bad???"),
299                         None => {}
300                 }
301
302                 let mut events = self.pending_events.lock().unwrap();
303                 events.push(events::Event::SendOpenChannel {
304                         node_id: their_network_key,
305                         msg: res,
306                 });
307                 Ok(())
308         }
309
310         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
311         /// more information.
312         pub fn list_channels(&self) -> Vec<ChannelDetails> {
313                 let channel_state = self.channel_state.lock().unwrap();
314                 let mut res = Vec::with_capacity(channel_state.by_id.len());
315                 for (channel_id, channel) in channel_state.by_id.iter() {
316                         res.push(ChannelDetails {
317                                 channel_id: (*channel_id).clone(),
318                                 short_channel_id: channel.get_short_channel_id(),
319                                 remote_network_id: channel.get_their_node_id(),
320                                 channel_value_satoshis: channel.get_value_satoshis(),
321                                 user_id: channel.get_user_id(),
322                         });
323                 }
324                 res
325         }
326
327         /// Gets the list of usable channels, in random order. Useful as an argument to
328         /// Router::get_route to ensure non-announced channels are used.
329         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
330                 let channel_state = self.channel_state.lock().unwrap();
331                 let mut res = Vec::with_capacity(channel_state.by_id.len());
332                 for (channel_id, channel) in channel_state.by_id.iter() {
333                         if channel.is_usable() {
334                                 res.push(ChannelDetails {
335                                         channel_id: (*channel_id).clone(),
336                                         short_channel_id: channel.get_short_channel_id(),
337                                         remote_network_id: channel.get_their_node_id(),
338                                         channel_value_satoshis: channel.get_value_satoshis(),
339                                         user_id: channel.get_user_id(),
340                                 });
341                         }
342                 }
343                 res
344         }
345
346         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
347         /// will be accepted on the given channel, and after additional timeout/the closing of all
348         /// pending HTLCs, the channel will be closed on chain.
349         /// May generate a SendShutdown event on success, which should be relayed.
350         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), HandleError> {
351                 let (res, node_id, chan_option) = {
352                         let mut channel_state_lock = self.channel_state.lock().unwrap();
353                         let channel_state = channel_state_lock.borrow_parts();
354                         match channel_state.by_id.entry(channel_id.clone()) {
355                                 hash_map::Entry::Occupied(mut chan_entry) => {
356                                         let res = chan_entry.get_mut().get_shutdown()?;
357                                         if chan_entry.get().is_shutdown() {
358                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
359                                                         channel_state.short_to_id.remove(&short_id);
360                                                 }
361                                                 (res, chan_entry.get().get_their_node_id(), Some(chan_entry.remove_entry().1))
362                                         } else { (res, chan_entry.get().get_their_node_id(), None) }
363                                 },
364                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "No such channel", action: None})
365                         }
366                 };
367                 for payment_hash in res.1 {
368                         // unknown_next_peer...I dunno who that is anymore....
369                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
370                 }
371                 let chan_update = if let Some(chan) = chan_option {
372                         if let Ok(update) = self.get_channel_update(&chan) {
373                                 Some(update)
374                         } else { None }
375                 } else { None };
376
377                 let mut events = self.pending_events.lock().unwrap();
378                 if let Some(update) = chan_update {
379                         events.push(events::Event::BroadcastChannelUpdate {
380                                 msg: update
381                         });
382                 }
383                 events.push(events::Event::SendShutdown {
384                         node_id,
385                         msg: res.0
386                 });
387
388                 Ok(())
389         }
390
391         #[inline]
392         fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<[u8; 32]>)) {
393                 let (local_txn, failed_htlcs) = shutdown_res;
394                 for payment_hash in failed_htlcs {
395                         // unknown_next_peer...I dunno who that is anymore....
396                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
397                 }
398                 for tx in local_txn {
399                         self.tx_broadcaster.broadcast_transaction(&tx);
400                 }
401                 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
402                 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
403                 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
404                 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
405                 //timeouts are hit and our claims confirm).
406         }
407
408         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
409         /// the chain and rejecting new HTLCs on the given channel.
410         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
411                 let mut chan = {
412                         let mut channel_state_lock = self.channel_state.lock().unwrap();
413                         let channel_state = channel_state_lock.borrow_parts();
414                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
415                                 if let Some(short_id) = chan.get_short_channel_id() {
416                                         channel_state.short_to_id.remove(&short_id);
417                                 }
418                                 chan
419                         } else {
420                                 return;
421                         }
422                 };
423                 self.finish_force_close_channel(chan.force_shutdown());
424                 let mut events = self.pending_events.lock().unwrap();
425                 if let Ok(update) = self.get_channel_update(&chan) {
426                         events.push(events::Event::BroadcastChannelUpdate {
427                                 msg: update
428                         });
429                 }
430         }
431
432         /// Force close all channels, immediately broadcasting the latest local commitment transaction
433         /// for each to the chain and rejecting new HTLCs on each.
434         pub fn force_close_all_channels(&self) {
435                 for chan in self.list_channels() {
436                         self.force_close_channel(&chan.channel_id);
437                 }
438         }
439
440         #[inline]
441         fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
442                 ({
443                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
444                         hmac.input(&shared_secret[..]);
445                         let mut res = [0; 32];
446                         hmac.raw_result(&mut res);
447                         res
448                 },
449                 {
450                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
451                         hmac.input(&shared_secret[..]);
452                         let mut res = [0; 32];
453                         hmac.raw_result(&mut res);
454                         res
455                 })
456         }
457
458         #[inline]
459         fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
460                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
461                 hmac.input(&shared_secret[..]);
462                 let mut res = [0; 32];
463                 hmac.raw_result(&mut res);
464                 res
465         }
466
467         #[inline]
468         fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
469                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
470                 hmac.input(&shared_secret[..]);
471                 let mut res = [0; 32];
472                 hmac.raw_result(&mut res);
473                 res
474         }
475
476         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
477         #[inline]
478         fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), HandleError> {
479                 let mut blinded_priv = session_priv.clone();
480                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
481                 let mut first_iteration = true;
482
483                 for hop in route.hops.iter() {
484                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
485
486                         let mut sha = Sha256::new();
487                         sha.input(&blinded_pub.serialize()[..]);
488                         sha.input(&shared_secret[..]);
489                         let mut blinding_factor = [0u8; 32];
490                         sha.result(&mut blinding_factor);
491
492                         if first_iteration {
493                                 blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
494                                 first_iteration = false;
495                         }
496                         let ephemeral_pubkey = blinded_pub;
497
498                         secp_call!(blinded_priv.mul_assign(secp_ctx, &secp_call!(SecretKey::from_slice(secp_ctx, &blinding_factor))));
499                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
500
501                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
502                 }
503
504                 Ok(())
505         }
506
507         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
508         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, HandleError> {
509                 let mut res = Vec::with_capacity(route.hops.len());
510
511                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
512                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
513
514                         res.push(OnionKeys {
515                                 #[cfg(test)]
516                                 shared_secret,
517                                 #[cfg(test)]
518                                 blinding_factor: _blinding_factor,
519                                 ephemeral_pubkey,
520                                 rho,
521                                 mu,
522                         });
523                 })?;
524
525                 Ok(res)
526         }
527
528         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
529         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), HandleError> {
530                 let mut cur_value_msat = 0u64;
531                 let mut cur_cltv = starting_htlc_offset;
532                 let mut last_short_channel_id = 0;
533                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
534                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
535                 unsafe { res.set_len(route.hops.len()); }
536
537                 for (idx, hop) in route.hops.iter().enumerate().rev() {
538                         // First hop gets special values so that it can check, on receipt, that everything is
539                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
540                         // the intended recipient).
541                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
542                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
543                         res[idx] = msgs::OnionHopData {
544                                 realm: 0,
545                                 data: msgs::OnionRealm0HopData {
546                                         short_channel_id: last_short_channel_id,
547                                         amt_to_forward: value_msat,
548                                         outgoing_cltv_value: cltv,
549                                 },
550                                 hmac: [0; 32],
551                         };
552                         cur_value_msat += hop.fee_msat;
553                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
554                                 return Err(HandleError{err: "Channel fees overflowed?!", action: None});
555                         }
556                         cur_cltv += hop.cltv_expiry_delta as u32;
557                         if cur_cltv >= 500000000 {
558                                 return Err(HandleError{err: "Channel CLTV overflowed?!", action: None});
559                         }
560                         last_short_channel_id = hop.short_channel_id;
561                 }
562                 Ok((res, cur_value_msat, cur_cltv))
563         }
564
565         #[inline]
566         fn shift_arr_right(arr: &mut [u8; 20*65]) {
567                 unsafe {
568                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
569                 }
570                 for i in 0..65 {
571                         arr[i] = 0;
572                 }
573         }
574
575         #[inline]
576         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
577                 assert_eq!(dst.len(), src.len());
578
579                 for i in 0..dst.len() {
580                         dst[i] ^= src[i];
581                 }
582         }
583
584         const ZERO:[u8; 21*65] = [0; 21*65];
585         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> Result<msgs::OnionPacket, HandleError> {
586                 let mut buf = Vec::with_capacity(21*65);
587                 buf.resize(21*65, 0);
588
589                 let filler = {
590                         let iters = payloads.len() - 1;
591                         let end_len = iters * 65;
592                         let mut res = Vec::with_capacity(end_len);
593                         res.resize(end_len, 0);
594
595                         for (i, keys) in onion_keys.iter().enumerate() {
596                                 if i == payloads.len() - 1 { continue; }
597                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
598                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
599                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
600                         }
601                         res
602                 };
603
604                 let mut packet_data = [0; 20*65];
605                 let mut hmac_res = [0; 32];
606
607                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
608                         ChannelManager::shift_arr_right(&mut packet_data);
609                         payload.hmac = hmac_res;
610                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
611
612                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
613                         chacha.process(&packet_data, &mut buf[0..20*65]);
614                         packet_data[..].copy_from_slice(&buf[0..20*65]);
615
616                         if i == 0 {
617                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
618                         }
619
620                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
621                         hmac.input(&packet_data);
622                         hmac.input(&associated_data[..]);
623                         hmac.raw_result(&mut hmac_res);
624                 }
625
626                 Ok(msgs::OnionPacket{
627                         version: 0,
628                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
629                         hop_data: packet_data,
630                         hmac: hmac_res,
631                 })
632         }
633
634         /// Encrypts a failure packet. raw_packet can either be a
635         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
636         fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
637                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
638
639                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
640                 packet_crypted.resize(raw_packet.len(), 0);
641                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
642                 chacha.process(&raw_packet, &mut packet_crypted[..]);
643                 msgs::OnionErrorPacket {
644                         data: packet_crypted,
645                 }
646         }
647
648         fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
649                 assert!(failure_data.len() <= 256 - 2);
650
651                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
652
653                 let failuremsg = {
654                         let mut res = Vec::with_capacity(2 + failure_data.len());
655                         res.push(((failure_type >> 8) & 0xff) as u8);
656                         res.push(((failure_type >> 0) & 0xff) as u8);
657                         res.extend_from_slice(&failure_data[..]);
658                         res
659                 };
660                 let pad = {
661                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
662                         res.resize(256 - 2 - failure_data.len(), 0);
663                         res
664                 };
665                 let mut packet = msgs::DecodedOnionErrorPacket {
666                         hmac: [0; 32],
667                         failuremsg: failuremsg,
668                         pad: pad,
669                 };
670
671                 let mut hmac = Hmac::new(Sha256::new(), &um);
672                 hmac.input(&packet.encode()[32..]);
673                 hmac.raw_result(&mut packet.hmac);
674
675                 packet
676         }
677
678         #[inline]
679         fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
680                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
681                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
682         }
683
684         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, Option<SharedSecret>, MutexGuard<ChannelHolder>) {
685                 macro_rules! get_onion_hash {
686                         () => {
687                                 {
688                                         let mut sha = Sha256::new();
689                                         sha.input(&msg.onion_routing_packet.hop_data);
690                                         let mut onion_hash = [0; 32];
691                                         sha.result(&mut onion_hash);
692                                         onion_hash
693                                 }
694                         }
695                 }
696
697                 if let Err(_) = msg.onion_routing_packet.public_key {
698                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
699                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
700                                 channel_id: msg.channel_id,
701                                 htlc_id: msg.htlc_id,
702                                 sha256_of_onion: get_onion_hash!(),
703                                 failure_code: 0x8000 | 0x4000 | 6,
704                         })), None, self.channel_state.lock().unwrap());
705                 }
706
707                 let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key);
708                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
709
710                 let mut channel_state = None;
711                 macro_rules! return_err {
712                         ($msg: expr, $err_code: expr, $data: expr) => {
713                                 {
714                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
715                                         if channel_state.is_none() {
716                                                 channel_state = Some(self.channel_state.lock().unwrap());
717                                         }
718                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
719                                                 channel_id: msg.channel_id,
720                                                 htlc_id: msg.htlc_id,
721                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
722                                         })), Some(shared_secret), channel_state.unwrap());
723                                 }
724                         }
725                 }
726
727                 if msg.onion_routing_packet.version != 0 {
728                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
729                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
730                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
731                         //receiving node would have to brute force to figure out which version was put in the
732                         //packet by the node that send us the message, in the case of hashing the hop_data, the
733                         //node knows the HMAC matched, so they already know what is there...
734                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
735                 }
736
737                 let mut hmac = Hmac::new(Sha256::new(), &mu);
738                 hmac.input(&msg.onion_routing_packet.hop_data);
739                 hmac.input(&msg.payment_hash);
740                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
741                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
742                 }
743
744                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
745                 let next_hop_data = {
746                         let mut decoded = [0; 65];
747                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
748                         match msgs::OnionHopData::decode(&decoded[..]) {
749                                 Err(err) => {
750                                         let error_code = match err {
751                                                 msgs::DecodeError::UnknownRealmByte => 0x4000 | 1,
752                                                 _ => 0x2000 | 2, // Should never happen
753                                         };
754                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
755                                 },
756                                 Ok(msg) => msg
757                         }
758                 };
759
760                 //TODO: Check that msg.cltv_expiry is within acceptable bounds!
761
762                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
763                                 // OUR PAYMENT!
764                                 if next_hop_data.data.amt_to_forward != msg.amount_msat {
765                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
766                                 }
767                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
768                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
769                                 }
770
771                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
772                                 // message, however that would leak that we are the recipient of this payment, so
773                                 // instead we stay symmetric with the forwarding case, only responding (after a
774                                 // delay) once they've send us a commitment_signed!
775
776                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
777                                         onion_packet: None,
778                                         payment_hash: msg.payment_hash.clone(),
779                                         short_channel_id: 0,
780                                         prev_short_channel_id: 0,
781                                         amt_to_forward: next_hop_data.data.amt_to_forward,
782                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
783                                 })
784                         } else {
785                                 let mut new_packet_data = [0; 20*65];
786                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
787                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
788
789                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
790
791                                 let blinding_factor = {
792                                         let mut sha = Sha256::new();
793                                         sha.input(&new_pubkey.serialize()[..]);
794                                         sha.input(&shared_secret[..]);
795                                         let mut res = [0u8; 32];
796                                         sha.result(&mut res);
797                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
798                                                 Err(_) => {
799                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
800                                                 },
801                                                 Ok(key) => key
802                                         }
803                                 };
804
805                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
806                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
807                                 }
808
809                                 let outgoing_packet = msgs::OnionPacket {
810                                         version: 0,
811                                         public_key: Ok(new_pubkey),
812                                         hop_data: new_packet_data,
813                                         hmac: next_hop_data.hmac.clone(),
814                                 };
815
816                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
817                                         onion_packet: Some(outgoing_packet),
818                                         payment_hash: msg.payment_hash.clone(),
819                                         short_channel_id: next_hop_data.data.short_channel_id,
820                                         prev_short_channel_id: 0,
821                                         amt_to_forward: next_hop_data.data.amt_to_forward,
822                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
823                                 })
824                         };
825
826                 channel_state = Some(self.channel_state.lock().unwrap());
827                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
828                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
829                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
830                                 let forwarding_id = match id_option {
831                                         None => {
832                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
833                                         },
834                                         Some(id) => id.clone(),
835                                 };
836                                 if let Some((err, code, chan_update)) = {
837                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
838                                         if !chan.is_live() {
839                                                 Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, self.get_channel_update(chan).unwrap()))
840                                         } else {
841                                                 let fee = amt_to_forward.checked_mul(self.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) });
842                                                 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward {
843                                                         Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, self.get_channel_update(chan).unwrap()))
844                                                 } else {
845                                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 {
846                                                                 Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, self.get_channel_update(chan).unwrap()))
847                                                         } else {
848                                                                 None
849                                                         }
850                                                 }
851                                         }
852                                 } {
853                                         return_err!(err, code, &chan_update.encode_with_len()[..]);
854                                 }
855                         }
856                 }
857
858                 (pending_forward_info, Some(shared_secret), channel_state.unwrap())
859         }
860
861         /// only fails if the channel does not yet have an assigned short_id
862         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
863                 let short_channel_id = match chan.get_short_channel_id() {
864                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
865                         Some(id) => id,
866                 };
867
868                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
869
870                 let unsigned = msgs::UnsignedChannelUpdate {
871                         chain_hash: self.genesis_hash,
872                         short_channel_id: short_channel_id,
873                         timestamp: chan.get_channel_update_count(),
874                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
875                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
876                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
877                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
878                         fee_proportional_millionths: self.fee_proportional_millionths,
879                         excess_data: Vec::new(),
880                 };
881
882                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
883                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key); //TODO Can we unwrap here?
884
885                 Ok(msgs::ChannelUpdate {
886                         signature: sig,
887                         contents: unsigned
888                 })
889         }
890
891         /// Sends a payment along a given route.
892         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
893         /// fields for more info.
894         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
895         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
896         /// next hop knows the preimage to payment_hash they can claim an additional amount as
897         /// specified in the last hop in the route! Thus, you should probably do your own
898         /// payment_preimage tracking (which you should already be doing as they represent "proof of
899         /// payment") and prevent double-sends yourself.
900         /// See-also docs on Channel::send_htlc_and_commit.
901         /// May generate a SendHTLCs event on success, which should be relayed.
902         pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), HandleError> {
903                 if route.hops.len() < 1 || route.hops.len() > 20 {
904                         return Err(HandleError{err: "Route didn't go anywhere/had bogus size", action: None});
905                 }
906                 let our_node_id = self.get_our_node_id();
907                 for (idx, hop) in route.hops.iter().enumerate() {
908                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
909                                 return Err(HandleError{err: "Route went through us but wasn't a simple rebalance loop to us", action: None});
910                         }
911                 }
912
913                 let session_priv = secp_call!(SecretKey::from_slice(&self.secp_ctx, &{
914                         let mut session_key = [0; 32];
915                         rng::fill_bytes(&mut session_key);
916                         session_key
917                 }));
918
919                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
920
921                 let onion_keys = ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv)?;
922                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
923                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash)?;
924
925                 let (first_hop_node_id, (update_add, commitment_signed, chan_monitor)) = {
926                         let mut channel_state_lock = self.channel_state.lock().unwrap();
927                         let channel_state = channel_state_lock.borrow_parts();
928
929                         let id = match channel_state.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
930                                 None => return Err(HandleError{err: "No channel available with first hop!", action: None}),
931                                 Some(id) => id.clone()
932                         };
933
934                         let claimable_htlc_entry = channel_state.claimable_htlcs.entry(payment_hash.clone());
935                         if let hash_map::Entry::Occupied(_) = claimable_htlc_entry {
936                                 return Err(HandleError{err: "Already had pending HTLC with the same payment_hash", action: None});
937                         }
938
939                         let res = {
940                                 let chan = channel_state.by_id.get_mut(&id).unwrap();
941                                 if chan.get_their_node_id() != route.hops.first().unwrap().pubkey {
942                                         return Err(HandleError{err: "Node ID mismatch on first hop!", action: None});
943                                 }
944                                 chan.send_htlc_and_commit(htlc_msat, payment_hash, htlc_cltv, onion_packet)?
945                         };
946
947                         let first_hop_node_id = route.hops.first().unwrap().pubkey;
948
949                         claimable_htlc_entry.or_insert(PendingOutboundHTLC::OutboundRoute {
950                                 route,
951                                 session_priv,
952                         });
953
954                         match res {
955                                 Some(msgs) => (first_hop_node_id, msgs),
956                                 None => return Ok(()),
957                         }
958                 };
959
960                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
961                         unimplemented!(); // maybe remove from claimable_htlcs?
962                 }
963
964                 let mut events = self.pending_events.lock().unwrap();
965                 events.push(events::Event::UpdateHTLCs {
966                         node_id: first_hop_node_id,
967                         updates: msgs::CommitmentUpdate {
968                                 update_add_htlcs: vec![update_add],
969                                 update_fulfill_htlcs: Vec::new(),
970                                 update_fail_htlcs: Vec::new(),
971                                 update_fail_malformed_htlcs: Vec::new(),
972                                 commitment_signed,
973                         },
974                 });
975                 Ok(())
976         }
977
978         /// Call this upon creation of a funding transaction for the given channel.
979         /// Panics if a funding transaction has already been provided for this channel.
980         /// May panic if the funding_txo is duplicative with some other channel (note that this should
981         /// be trivially prevented by using unique funding transaction keys per-channel).
982         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
983
984                 macro_rules! add_pending_event {
985                         ($event: expr) => {
986                                 {
987                                         let mut pending_events = self.pending_events.lock().unwrap();
988                                         pending_events.push($event);
989                                 }
990                         }
991                 }
992
993                 let (chan, msg, chan_monitor) = {
994                         let mut channel_state = self.channel_state.lock().unwrap();
995                         match channel_state.by_id.remove(temporary_channel_id) {
996                                 Some(mut chan) => {
997                                         match chan.get_outbound_funding_created(funding_txo) {
998                                                 Ok(funding_msg) => {
999                                                         (chan, funding_msg.0, funding_msg.1)
1000                                                 },
1001                                                 Err(e) => {
1002                                                         log_error!(self, "Got bad signatures: {}!", e.err);
1003                                                         mem::drop(channel_state);
1004                                                         add_pending_event!(events::Event::HandleError {
1005                                                                 node_id: chan.get_their_node_id(),
1006                                                                 action: e.action,
1007                                                         });
1008                                                         return;
1009                                                 },
1010                                         }
1011                                 },
1012                                 None => return
1013                         }
1014                 }; // Release channel lock for install_watch_outpoint call,
1015                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1016                         unimplemented!(); // maybe remove from claimable_htlcs?
1017                 }
1018                 add_pending_event!(events::Event::SendFundingCreated {
1019                         node_id: chan.get_their_node_id(),
1020                         msg: msg,
1021                 });
1022
1023                 let mut channel_state = self.channel_state.lock().unwrap();
1024                 match channel_state.by_id.entry(chan.channel_id()) {
1025                         hash_map::Entry::Occupied(_) => {
1026                                 panic!("Generated duplicate funding txid?");
1027                         },
1028                         hash_map::Entry::Vacant(e) => {
1029                                 e.insert(chan);
1030                         }
1031                 }
1032         }
1033
1034         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1035                 if !chan.should_announce() { return None }
1036
1037                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1038                         Ok(res) => res,
1039                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1040                 };
1041                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1042                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1043
1044                 Some(msgs::AnnouncementSignatures {
1045                         channel_id: chan.channel_id(),
1046                         short_channel_id: chan.get_short_channel_id().unwrap(),
1047                         node_signature: our_node_sig,
1048                         bitcoin_signature: our_bitcoin_sig,
1049                 })
1050         }
1051
1052         /// Processes HTLCs which are pending waiting on random forward delay.
1053         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1054         /// Will likely generate further events.
1055         pub fn process_pending_htlc_forwards(&self) {
1056                 let mut new_events = Vec::new();
1057                 let mut failed_forwards = Vec::new();
1058                 {
1059                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1060                         let channel_state = channel_state_lock.borrow_parts();
1061
1062                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1063                                 return;
1064                         }
1065
1066                         for (short_chan_id, pending_forwards) in channel_state.forward_htlcs.drain() {
1067                                 if short_chan_id != 0 {
1068                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1069                                                 Some(chan_id) => chan_id.clone(),
1070                                                 None => {
1071                                                         failed_forwards.reserve(pending_forwards.len());
1072                                                         for forward_info in pending_forwards {
1073                                                                 failed_forwards.push((forward_info.payment_hash, 0x4000 | 10, None));
1074                                                         }
1075                                                         continue;
1076                                                 }
1077                                         };
1078                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1079
1080                                         let mut add_htlc_msgs = Vec::new();
1081                                         for forward_info in pending_forwards {
1082                                                 match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, forward_info.onion_packet.unwrap()) {
1083                                                         Err(_e) => {
1084                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1085                                                                 failed_forwards.push((forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1086                                                                 continue;
1087                                                         },
1088                                                         Ok(update_add) => {
1089                                                                 match update_add {
1090                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1091                                                                         None => {
1092                                                                                 // Nothing to do here...we're waiting on a remote
1093                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1094                                                                                 // will automatically handle building the update_add_htlc and
1095                                                                                 // commitment_signed messages when we can.
1096                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1097                                                                                 // as we don't really want others relying on us relaying through
1098                                                                                 // this channel currently :/.
1099                                                                         }
1100                                                                 }
1101                                                         }
1102                                                 }
1103                                         }
1104
1105                                         if !add_htlc_msgs.is_empty() {
1106                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1107                                                         Ok(res) => res,
1108                                                         Err(_e) => {
1109                                                                 //TODO: Handle...this is bad!
1110                                                                 continue;
1111                                                         },
1112                                                 };
1113                                                 new_events.push((Some(monitor), events::Event::UpdateHTLCs {
1114                                                         node_id: forward_chan.get_their_node_id(),
1115                                                         updates: msgs::CommitmentUpdate {
1116                                                                 update_add_htlcs: add_htlc_msgs,
1117                                                                 update_fulfill_htlcs: Vec::new(),
1118                                                                 update_fail_htlcs: Vec::new(),
1119                                                                 update_fail_malformed_htlcs: Vec::new(),
1120                                                                 commitment_signed: commitment_msg,
1121                                                         },
1122                                                 }));
1123                                         }
1124                                 } else {
1125                                         for forward_info in pending_forwards {
1126                                                 new_events.push((None, events::Event::PaymentReceived {
1127                                                         payment_hash: forward_info.payment_hash,
1128                                                         amt: forward_info.amt_to_forward,
1129                                                 }));
1130                                         }
1131                                 }
1132                         }
1133                 }
1134
1135                 for failed_forward in failed_forwards.drain(..) {
1136                         match failed_forward.2 {
1137                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failed_forward.0, HTLCFailReason::Reason { failure_code: failed_forward.1, data: Vec::new() }),
1138                                 Some(chan_update) => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failed_forward.0, HTLCFailReason::Reason { failure_code: failed_forward.1, data: chan_update.encode_with_len() }),
1139                         };
1140                 }
1141
1142                 if new_events.is_empty() { return }
1143
1144                 new_events.retain(|event| {
1145                         if let &Some(ref monitor) = &event.0 {
1146                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor.clone()) {
1147                                         unimplemented!();// but def dont push the event...
1148                                 }
1149                         }
1150                         true
1151                 });
1152
1153                 let mut events = self.pending_events.lock().unwrap();
1154                 events.reserve(new_events.len());
1155                 for event in new_events.drain(..) {
1156                         events.push(event.1);
1157                 }
1158         }
1159
1160         /// Indicates that the preimage for payment_hash is unknown after a PaymentReceived event.
1161         pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32]) -> bool {
1162                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: Vec::new() })
1163         }
1164
1165         /// Fails an HTLC backwards to the sender of it to us.
1166         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1167         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1168         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1169         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1170         /// still-available channels.
1171         fn fail_htlc_backwards_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, payment_hash: &[u8; 32], onion_error: HTLCFailReason) -> bool {
1172                 let mut pending_htlc = {
1173                         match channel_state.claimable_htlcs.remove(payment_hash) {
1174                                 Some(pending_htlc) => pending_htlc,
1175                                 None => return false,
1176                         }
1177                 };
1178
1179                 match pending_htlc {
1180                         PendingOutboundHTLC::CycledRoute { source_short_channel_id, incoming_packet_shared_secret, route, session_priv } => {
1181                                 channel_state.claimable_htlcs.insert(payment_hash.clone(), PendingOutboundHTLC::OutboundRoute {
1182                                         route,
1183                                         session_priv,
1184                                 });
1185                                 pending_htlc = PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret };
1186                         },
1187                         _ => {}
1188                 }
1189
1190                 match pending_htlc {
1191                         PendingOutboundHTLC::CycledRoute { .. } => unreachable!(),
1192                         PendingOutboundHTLC::OutboundRoute { .. } => {
1193                                 mem::drop(channel_state);
1194
1195                                 let mut pending_events = self.pending_events.lock().unwrap();
1196                                 pending_events.push(events::Event::PaymentFailed {
1197                                         payment_hash: payment_hash.clone()
1198                                 });
1199                                 false
1200                         },
1201                         PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret } => {
1202                                 let err_packet = match onion_error {
1203                                         HTLCFailReason::Reason { failure_code, data } => {
1204                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1205                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1206                                         },
1207                                         HTLCFailReason::ErrorPacket { err } => {
1208                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1209                                         }
1210                                 };
1211
1212                                 let (node_id, fail_msgs) = {
1213                                         let chan_id = match channel_state.short_to_id.get(&source_short_channel_id) {
1214                                                 Some(chan_id) => chan_id.clone(),
1215                                                 None => return false
1216                                         };
1217
1218                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1219                                         match chan.get_update_fail_htlc_and_commit(payment_hash, err_packet) {
1220                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1221                                                 Err(_e) => {
1222                                                         //TODO: Do something with e?
1223                                                         return false;
1224                                                 },
1225                                         }
1226                                 };
1227
1228                                 match fail_msgs {
1229                                         Some((msg, commitment_msg, chan_monitor)) => {
1230                                                 mem::drop(channel_state);
1231
1232                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1233                                                         unimplemented!();// but def dont push the event...
1234                                                 }
1235
1236                                                 let mut pending_events = self.pending_events.lock().unwrap();
1237                                                 pending_events.push(events::Event::UpdateHTLCs {
1238                                                         node_id,
1239                                                         updates: msgs::CommitmentUpdate {
1240                                                                 update_add_htlcs: Vec::new(),
1241                                                                 update_fulfill_htlcs: Vec::new(),
1242                                                                 update_fail_htlcs: vec![msg],
1243                                                                 update_fail_malformed_htlcs: Vec::new(),
1244                                                                 commitment_signed: commitment_msg,
1245                                                         },
1246                                                 });
1247                                         },
1248                                         None => {},
1249                                 }
1250
1251                                 true
1252                         },
1253                 }
1254         }
1255
1256         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1257         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1258         /// should probably kick the net layer to go send messages if this returns true!
1259         /// May panic if called except in response to a PaymentReceived event.
1260         pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1261                 self.claim_funds_internal(payment_preimage, true)
1262         }
1263         fn claim_funds_internal(&self, payment_preimage: [u8; 32], from_user: bool) -> bool {
1264                 let mut sha = Sha256::new();
1265                 sha.input(&payment_preimage);
1266                 let mut payment_hash = [0; 32];
1267                 sha.result(&mut payment_hash);
1268
1269                 let mut channel_state = self.channel_state.lock().unwrap();
1270                 let mut pending_htlc = {
1271                         match channel_state.claimable_htlcs.remove(&payment_hash) {
1272                                 Some(pending_htlc) => pending_htlc,
1273                                 None => return false,
1274                         }
1275                 };
1276
1277                 match pending_htlc {
1278                         PendingOutboundHTLC::CycledRoute { source_short_channel_id, incoming_packet_shared_secret, route, session_priv } => {
1279                                 if from_user { // This was the end hop back to us
1280                                         pending_htlc = PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret };
1281                                         channel_state.claimable_htlcs.insert(payment_hash, PendingOutboundHTLC::OutboundRoute { route, session_priv });
1282                                 } else { // This came from the first upstream node
1283                                         // Bank error in our favor! Maybe we should tell the user this somehow???
1284                                         pending_htlc = PendingOutboundHTLC::OutboundRoute { route, session_priv };
1285                                         channel_state.claimable_htlcs.insert(payment_hash, PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret });
1286                                 }
1287                         },
1288                         _ => {},
1289                 }
1290
1291                 match pending_htlc {
1292                         PendingOutboundHTLC::CycledRoute { .. } => unreachable!(),
1293                         PendingOutboundHTLC::OutboundRoute { .. } => {
1294                                 if from_user {
1295                                         panic!("Called claim_funds with a preimage for an outgoing payment. There is nothing we can do with this, and something is seriously wrong if you knew this...");
1296                                 }
1297                                 mem::drop(channel_state);
1298                                 let mut pending_events = self.pending_events.lock().unwrap();
1299                                 pending_events.push(events::Event::PaymentSent {
1300                                         payment_preimage
1301                                 });
1302                                 false
1303                         },
1304                         PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, .. } => {
1305                                 let (node_id, fulfill_msgs) = {
1306                                         let chan_id = match channel_state.short_to_id.get(&source_short_channel_id) {
1307                                                 Some(chan_id) => chan_id.clone(),
1308                                                 None => {
1309                                                         // TODO: There is probably a channel manager somewhere that needs to
1310                                                         // learn the preimage as the channel already hit the chain and that's
1311                                                         // why its missing.
1312                                                         return false
1313                                                 }
1314                                         };
1315
1316                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1317                                         match chan.get_update_fulfill_htlc_and_commit(payment_preimage) {
1318                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1319                                                 Err(_e) => {
1320                                                         // TODO: There is probably a channel manager somewhere that needs to
1321                                                         // learn the preimage as the channel may be about to hit the chain.
1322                                                         //TODO: Do something with e?
1323                                                         return false;
1324                                                 },
1325                                         }
1326                                 };
1327
1328                                 mem::drop(channel_state);
1329                                 if let Some(chan_monitor) = fulfill_msgs.1 {
1330                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1331                                                 unimplemented!();// but def dont push the event...
1332                                         }
1333                                 }
1334
1335                                 if let Some((msg, commitment_msg)) = fulfill_msgs.0 {
1336                                         let mut pending_events = self.pending_events.lock().unwrap();
1337                                         pending_events.push(events::Event::UpdateHTLCs {
1338                                                 node_id: node_id,
1339                                                 updates: msgs::CommitmentUpdate {
1340                                                         update_add_htlcs: Vec::new(),
1341                                                         update_fulfill_htlcs: vec![msg],
1342                                                         update_fail_htlcs: Vec::new(),
1343                                                         update_fail_malformed_htlcs: Vec::new(),
1344                                                         commitment_signed: commitment_msg,
1345                                                 }
1346                                         });
1347                                 }
1348                                 true
1349                         },
1350                 }
1351         }
1352
1353         /// Gets the node_id held by this ChannelManager
1354         pub fn get_our_node_id(&self) -> PublicKey {
1355                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1356         }
1357
1358         /// Used to restore channels to normal operation after a
1359         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1360         /// operation.
1361         pub fn test_restore_channel_monitor(&self) {
1362                 unimplemented!();
1363         }
1364 }
1365
1366 impl events::EventsProvider for ChannelManager {
1367         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
1368                 let mut pending_events = self.pending_events.lock().unwrap();
1369                 let mut ret = Vec::new();
1370                 mem::swap(&mut ret, &mut *pending_events);
1371                 ret
1372         }
1373 }
1374
1375 impl ChainListener for ChannelManager {
1376         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
1377                 let mut new_events = Vec::new();
1378                 let mut failed_channels = Vec::new();
1379                 {
1380                         let mut channel_lock = self.channel_state.lock().unwrap();
1381                         let channel_state = channel_lock.borrow_parts();
1382                         let short_to_id = channel_state.short_to_id;
1383                         channel_state.by_id.retain(|_, channel| {
1384                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
1385                                 if let Ok(Some(funding_locked)) = chan_res {
1386                                         let announcement_sigs = self.get_announcement_sigs(channel);
1387                                         new_events.push(events::Event::SendFundingLocked {
1388                                                 node_id: channel.get_their_node_id(),
1389                                                 msg: funding_locked,
1390                                                 announcement_sigs: announcement_sigs
1391                                         });
1392                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
1393                                 } else if let Err(e) = chan_res {
1394                                         new_events.push(events::Event::HandleError {
1395                                                 node_id: channel.get_their_node_id(),
1396                                                 action: e.action,
1397                                         });
1398                                         if channel.is_shutdown() {
1399                                                 return false;
1400                                         }
1401                                 }
1402                                 if let Some(funding_txo) = channel.get_funding_txo() {
1403                                         for tx in txn_matched {
1404                                                 for inp in tx.input.iter() {
1405                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
1406                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1407                                                                         short_to_id.remove(&short_id);
1408                                                                 }
1409                                                                 // It looks like our counterparty went on-chain. We go ahead and
1410                                                                 // broadcast our latest local state as well here, just in case its
1411                                                                 // some kind of SPV attack, though we expect these to be dropped.
1412                                                                 failed_channels.push(channel.force_shutdown());
1413                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1414                                                                         new_events.push(events::Event::BroadcastChannelUpdate {
1415                                                                                 msg: update
1416                                                                         });
1417                                                                 }
1418                                                                 return false;
1419                                                         }
1420                                                 }
1421                                         }
1422                                 }
1423                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
1424                                         if let Some(short_id) = channel.get_short_channel_id() {
1425                                                 short_to_id.remove(&short_id);
1426                                         }
1427                                         failed_channels.push(channel.force_shutdown());
1428                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
1429                                         // the latest local tx for us, so we should skip that here (it doesn't really
1430                                         // hurt anything, but does make tests a bit simpler).
1431                                         failed_channels.last_mut().unwrap().0 = Vec::new();
1432                                         if let Ok(update) = self.get_channel_update(&channel) {
1433                                                 new_events.push(events::Event::BroadcastChannelUpdate {
1434                                                         msg: update
1435                                                 });
1436                                         }
1437                                         return false;
1438                                 }
1439                                 true
1440                         });
1441                 }
1442                 for failure in failed_channels.drain(..) {
1443                         self.finish_force_close_channel(failure);
1444                 }
1445                 let mut pending_events = self.pending_events.lock().unwrap();
1446                 for funding_locked in new_events.drain(..) {
1447                         pending_events.push(funding_locked);
1448                 }
1449                 self.latest_block_height.store(height as usize, Ordering::Release);
1450         }
1451
1452         /// We force-close the channel without letting our counterparty participate in the shutdown
1453         fn block_disconnected(&self, header: &BlockHeader) {
1454                 let mut new_events = Vec::new();
1455                 let mut failed_channels = Vec::new();
1456                 {
1457                         let mut channel_lock = self.channel_state.lock().unwrap();
1458                         let channel_state = channel_lock.borrow_parts();
1459                         let short_to_id = channel_state.short_to_id;
1460                         channel_state.by_id.retain(|_,  v| {
1461                                 if v.block_disconnected(header) {
1462                                         if let Some(short_id) = v.get_short_channel_id() {
1463                                                 short_to_id.remove(&short_id);
1464                                         }
1465                                         failed_channels.push(v.force_shutdown());
1466                                         if let Ok(update) = self.get_channel_update(&v) {
1467                                                 new_events.push(events::Event::BroadcastChannelUpdate {
1468                                                         msg: update
1469                                                 });
1470                                         }
1471                                         false
1472                                 } else {
1473                                         true
1474                                 }
1475                         });
1476                 }
1477                 for failure in failed_channels.drain(..) {
1478                         self.finish_force_close_channel(failure);
1479                 }
1480                 if !new_events.is_empty() {
1481                         let mut pending_events = self.pending_events.lock().unwrap();
1482                         for funding_locked in new_events.drain(..) {
1483                                 pending_events.push(funding_locked);
1484                         }
1485                 }
1486                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
1487         }
1488 }
1489
1490 impl ChannelMessageHandler for ChannelManager {
1491         //TODO: Handle errors and close channel (or so)
1492         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, HandleError> {
1493                 if msg.chain_hash != self.genesis_hash {
1494                         return Err(HandleError{err: "Unknown genesis block hash", action: None});
1495                 }
1496                 let mut channel_state = self.channel_state.lock().unwrap();
1497                 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
1498                         return Err(HandleError{err: "temporary_channel_id collision!", action: None});
1499                 }
1500
1501                 let chan_keys = if cfg!(feature = "fuzztarget") {
1502                         ChannelKeys {
1503                                 funding_key:               SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]).unwrap(),
1504                                 revocation_base_key:       SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0]).unwrap(),
1505                                 payment_base_key:          SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]).unwrap(),
1506                                 delayed_payment_base_key:  SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0]).unwrap(),
1507                                 htlc_base_key:             SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0]).unwrap(),
1508                                 channel_close_key:         SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0]).unwrap(),
1509                                 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0]).unwrap(),
1510                                 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1511                         }
1512                 } else {
1513                         let mut key_seed = [0u8; 32];
1514                         rng::fill_bytes(&mut key_seed);
1515                         match ChannelKeys::new_from_seed(&key_seed) {
1516                                 Ok(key) => key,
1517                                 Err(_) => panic!("RNG is busted!")
1518                         }
1519                 };
1520
1521                 let channel = Channel::new_from_req(&*self.fee_estimator, chan_keys, their_node_id.clone(), msg, 0, false, self.announce_channels_publicly, Arc::clone(&self.logger))?;
1522                 let accept_msg = channel.get_accept_channel()?;
1523                 channel_state.by_id.insert(channel.channel_id(), channel);
1524                 Ok(accept_msg)
1525         }
1526
1527         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
1528                 let (value, output_script, user_id) = {
1529                         let mut channel_state = self.channel_state.lock().unwrap();
1530                         match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
1531                                 Some(chan) => {
1532                                         if chan.get_their_node_id() != *their_node_id {
1533                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1534                                         }
1535                                         chan.accept_channel(&msg)?;
1536                                         (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
1537                                 },
1538                                 None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1539                         }
1540                 };
1541                 let mut pending_events = self.pending_events.lock().unwrap();
1542                 pending_events.push(events::Event::FundingGenerationReady {
1543                         temporary_channel_id: msg.temporary_channel_id,
1544                         channel_value_satoshis: value,
1545                         output_script: output_script,
1546                         user_channel_id: user_id,
1547                 });
1548                 Ok(())
1549         }
1550
1551         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, HandleError> {
1552                 let (chan, funding_msg, monitor_update) = {
1553                         let mut channel_state = self.channel_state.lock().unwrap();
1554                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1555                                 hash_map::Entry::Occupied(mut chan) => {
1556                                         if chan.get().get_their_node_id() != *their_node_id {
1557                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1558                                         }
1559                                         match chan.get_mut().funding_created(msg) {
1560                                                 Ok((funding_msg, monitor_update)) => {
1561                                                         (chan.remove(), funding_msg, monitor_update)
1562                                                 },
1563                                                 Err(e) => {
1564                                                         //TODO: Possibly remove the channel depending on e.action
1565                                                         return Err(e);
1566                                                 }
1567                                         }
1568                                 },
1569                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1570                         }
1571                 }; // Release channel lock for install_watch_outpoint call,
1572                    // note that this means if the remote end is misbehaving and sends a message for the same
1573                    // channel back-to-back with funding_created, we'll end up thinking they sent a message
1574                    // for a bogus channel.
1575                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1576                         unimplemented!();
1577                 }
1578                 let mut channel_state = self.channel_state.lock().unwrap();
1579                 match channel_state.by_id.entry(funding_msg.channel_id) {
1580                         hash_map::Entry::Occupied(_) => {
1581                                 return Err(HandleError {
1582                                         err: "Duplicate channel_id!",
1583                                         action: Some(msgs::ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id: funding_msg.channel_id, data: "Already had channel with the new channel_id".to_owned() } })
1584                                 });
1585                         },
1586                         hash_map::Entry::Vacant(e) => {
1587                                 e.insert(chan);
1588                         }
1589                 }
1590                 Ok(funding_msg)
1591         }
1592
1593         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
1594                 let (funding_txo, user_id, monitor) = {
1595                         let mut channel_state = self.channel_state.lock().unwrap();
1596                         match channel_state.by_id.get_mut(&msg.channel_id) {
1597                                 Some(chan) => {
1598                                         if chan.get_their_node_id() != *their_node_id {
1599                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1600                                         }
1601                                         let chan_monitor = chan.funding_signed(&msg)?;
1602                                         (chan.get_funding_txo().unwrap(), chan.get_user_id(), chan_monitor)
1603                                 },
1604                                 None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1605                         }
1606                 };
1607                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1608                         unimplemented!();
1609                 }
1610                 let mut pending_events = self.pending_events.lock().unwrap();
1611                 pending_events.push(events::Event::FundingBroadcastSafe {
1612                         funding_txo: funding_txo,
1613                         user_channel_id: user_id,
1614                 });
1615                 Ok(())
1616         }
1617
1618         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
1619                 let mut channel_state = self.channel_state.lock().unwrap();
1620                 match channel_state.by_id.get_mut(&msg.channel_id) {
1621                         Some(chan) => {
1622                                 if chan.get_their_node_id() != *their_node_id {
1623                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1624                                 }
1625                                 chan.funding_locked(&msg)?;
1626                                 return Ok(self.get_announcement_sigs(chan));
1627                         },
1628                         None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1629                 };
1630         }
1631
1632         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), HandleError> {
1633                 let (res, chan_option) = {
1634                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1635                         let channel_state = channel_state_lock.borrow_parts();
1636
1637                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1638                                 hash_map::Entry::Occupied(mut chan_entry) => {
1639                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1640                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1641                                         }
1642                                         let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg)?;
1643                                         if chan_entry.get().is_shutdown() {
1644                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1645                                                         channel_state.short_to_id.remove(&short_id);
1646                                                 }
1647                                                 (res, Some(chan_entry.remove_entry().1))
1648                                         } else { (res, None) }
1649                                 },
1650                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1651                         }
1652                 };
1653                 for payment_hash in res.2 {
1654                         // unknown_next_peer...I dunno who that is anymore....
1655                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1656                 }
1657                 if let Some(chan) = chan_option {
1658                         if let Ok(update) = self.get_channel_update(&chan) {
1659                                 let mut events = self.pending_events.lock().unwrap();
1660                                 events.push(events::Event::BroadcastChannelUpdate {
1661                                         msg: update
1662                                 });
1663                         }
1664                 }
1665                 Ok((res.0, res.1))
1666         }
1667
1668         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, HandleError> {
1669                 let (res, chan_option) = {
1670                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1671                         let channel_state = channel_state_lock.borrow_parts();
1672                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1673                                 hash_map::Entry::Occupied(mut chan_entry) => {
1674                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1675                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1676                                         }
1677                                         let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg)?;
1678                                         if res.1.is_some() {
1679                                                 // We're done with this channel, we've got a signed closing transaction and
1680                                                 // will send the closing_signed back to the remote peer upon return. This
1681                                                 // also implies there are no pending HTLCs left on the channel, so we can
1682                                                 // fully delete it from tracking (the channel monitor is still around to
1683                                                 // watch for old state broadcasts)!
1684                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1685                                                         channel_state.short_to_id.remove(&short_id);
1686                                                 }
1687                                                 (res, Some(chan_entry.remove_entry().1))
1688                                         } else { (res, None) }
1689                                 },
1690                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1691                         }
1692                 };
1693                 if let Some(broadcast_tx) = res.1 {
1694                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1695                 }
1696                 if let Some(chan) = chan_option {
1697                         if let Ok(update) = self.get_channel_update(&chan) {
1698                                 let mut events = self.pending_events.lock().unwrap();
1699                                 events.push(events::Event::BroadcastChannelUpdate {
1700                                         msg: update
1701                                 });
1702                         }
1703                 }
1704                 Ok(res.0)
1705         }
1706
1707         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
1708                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1709                 //determine the state of the payment based on our response/if we forward anything/the time
1710                 //we take to respond. We should take care to avoid allowing such an attack.
1711                 //
1712                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1713                 //us repeatedly garbled in different ways, and compare our error messages, which are
1714                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1715                 //but we should prevent it anyway.
1716
1717                 let (mut pending_forward_info, shared_secret, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1718                 let channel_state = channel_state_lock.borrow_parts();
1719
1720                 let claimable_htlcs_entry = channel_state.claimable_htlcs.entry(msg.payment_hash.clone());
1721
1722                 // We dont correctly handle payments that route through us twice on their way to their
1723                 // destination. That's OK since those nodes are probably busted or trying to do network
1724                 // mapping through repeated loops. In either case, we want them to stop talking to us, so
1725                 // we send permanent_node_failure.
1726                 let mut will_forward = false;
1727                 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { short_channel_id, .. }) = pending_forward_info {
1728                         if let &hash_map::Entry::Occupied(ref e) = &claimable_htlcs_entry {
1729                                 let mut acceptable_cycle = false;
1730                                 if let &PendingOutboundHTLC::OutboundRoute { .. } = e.get() {
1731                                         acceptable_cycle = short_channel_id == 0;
1732                                 }
1733                                 if !acceptable_cycle {
1734                                         log_info!(self, "Failed to accept incoming HTLC: Payment looped through us twice");
1735                                         pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1736                                                 channel_id: msg.channel_id,
1737                                                 htlc_id: msg.htlc_id,
1738                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret.unwrap(), 0x4000 | 0x2000 | 2, &[0;0]),
1739                                         }));
1740                                 } else {
1741                                         will_forward = true;
1742                                 }
1743                         } else {
1744                                 will_forward = true;
1745                         }
1746                 }
1747
1748                 let (source_short_channel_id, res) = match channel_state.by_id.get_mut(&msg.channel_id) {
1749                         Some(chan) => {
1750                                 if chan.get_their_node_id() != *their_node_id {
1751                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1752                                 }
1753                                 if !chan.is_usable() {
1754                                         return Err(HandleError{err: "Channel not yet available for receiving HTLCs", action: None});
1755                                 }
1756                                 let short_channel_id = chan.get_short_channel_id().unwrap();
1757                                 if let PendingHTLCStatus::Forward(ref mut forward_info) = pending_forward_info {
1758                                         forward_info.prev_short_channel_id = short_channel_id;
1759                                 }
1760                                 (short_channel_id, chan.update_add_htlc(&msg, pending_forward_info)?)
1761                         },
1762                         None => return Err(HandleError{err: "Failed to find corresponding channel", action: None}),
1763                 };
1764
1765                 if will_forward {
1766                         match claimable_htlcs_entry {
1767                                 hash_map::Entry::Occupied(mut e) => {
1768                                         let outbound_route = e.get_mut();
1769                                         let (route, session_priv) = match outbound_route {
1770                                                 &mut PendingOutboundHTLC::OutboundRoute { ref route, ref session_priv } => {
1771                                                         (route.clone(), session_priv.clone())
1772                                                 },
1773                                                 _ => unreachable!(),
1774                                         };
1775                                         *outbound_route = PendingOutboundHTLC::CycledRoute {
1776                                                 source_short_channel_id,
1777                                                 incoming_packet_shared_secret: shared_secret.unwrap(),
1778                                                 route,
1779                                                 session_priv,
1780                                         };
1781                                 },
1782                                 hash_map::Entry::Vacant(e) => {
1783                                         e.insert(PendingOutboundHTLC::IntermediaryHopData {
1784                                                 source_short_channel_id,
1785                                                 incoming_packet_shared_secret: shared_secret.unwrap(),
1786                                         });
1787                                 }
1788                         }
1789                 }
1790
1791                 Ok(res)
1792         }
1793
1794         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
1795                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1796                 // Claim funds first, cause we don't really care if the channel we received the message on
1797                 // is broken, we may have enough info to get our own money!
1798                 self.claim_funds_internal(msg.payment_preimage.clone(), false);
1799
1800                 let mut channel_state = self.channel_state.lock().unwrap();
1801                 match channel_state.by_id.get_mut(&msg.channel_id) {
1802                         Some(chan) => {
1803                                 if chan.get_their_node_id() != *their_node_id {
1804                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1805                                 }
1806                                 chan.update_fulfill_htlc(&msg)
1807                         },
1808                         None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1809                 }
1810         }
1811
1812         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, HandleError> {
1813                 let mut channel_state = self.channel_state.lock().unwrap();
1814                 let payment_hash = match channel_state.by_id.get_mut(&msg.channel_id) {
1815                         Some(chan) => {
1816                                 if chan.get_their_node_id() != *their_node_id {
1817                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1818                                 }
1819                                 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() })
1820                         },
1821                         None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1822                 }?;
1823
1824                 if let Some(pending_htlc) = channel_state.claimable_htlcs.get(&payment_hash) {
1825                         match pending_htlc {
1826                                 &PendingOutboundHTLC::OutboundRoute { ref route, ref session_priv } => {
1827                                         // Handle packed channel/node updates for passing back for the route handler
1828                                         let mut packet_decrypted = msg.reason.data.clone();
1829                                         let mut res = None;
1830                                         Self::construct_onion_keys_callback(&self.secp_ctx, &route, &session_priv, |shared_secret, _, _, route_hop| {
1831                                                 if res.is_some() { return; }
1832
1833                                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
1834
1835                                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1836                                                 decryption_tmp.resize(packet_decrypted.len(), 0);
1837                                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1838                                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1839                                                 packet_decrypted = decryption_tmp;
1840
1841                                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::decode(&packet_decrypted) {
1842                                                         if err_packet.failuremsg.len() >= 2 {
1843                                                                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
1844
1845                                                                 let mut hmac = Hmac::new(Sha256::new(), &um);
1846                                                                 hmac.input(&err_packet.encode()[32..]);
1847                                                                 let mut calc_tag = [0u8; 32];
1848                                                                 hmac.raw_result(&mut calc_tag);
1849                                                                 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
1850                                                                         const UNKNOWN_CHAN: u16 = 0x4000|10;
1851                                                                         const TEMP_CHAN_FAILURE: u16 = 0x4000|7;
1852                                                                         match byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]) {
1853                                                                                 TEMP_CHAN_FAILURE => {
1854                                                                                         if err_packet.failuremsg.len() >= 4 {
1855                                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[2..4]) as usize;
1856                                                                                                 if err_packet.failuremsg.len() >= 4 + update_len {
1857                                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::decode(&err_packet.failuremsg[4..4 + update_len]) {
1858                                                                                                                 res = Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1859                                                                                                                         msg: chan_update,
1860                                                                                                                 });
1861                                                                                                         }
1862                                                                                                 }
1863                                                                                         }
1864                                                                                 },
1865                                                                                 UNKNOWN_CHAN => {
1866                                                                                         // No such next-hop. We know this came from the
1867                                                                                         // current node as the HMAC validated.
1868                                                                                         res = Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1869                                                                                                 short_channel_id: route_hop.short_channel_id
1870                                                                                         });
1871                                                                                 },
1872                                                                                 _ => {}, //TODO: Enumerate all of these!
1873                                                                         }
1874                                                                 }
1875                                                         }
1876                                                 }
1877                                         }).unwrap();
1878                                         Ok(res)
1879                                 },
1880                                 _ => { Ok(None) },
1881                         }
1882                 } else {
1883                         Ok(None)
1884                 }
1885         }
1886
1887         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
1888                 let mut channel_state = self.channel_state.lock().unwrap();
1889                 match channel_state.by_id.get_mut(&msg.channel_id) {
1890                         Some(chan) => {
1891                                 if chan.get_their_node_id() != *their_node_id {
1892                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1893                                 }
1894                                 chan.update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() })
1895                         },
1896                         None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1897                 }
1898         }
1899
1900         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), HandleError> {
1901                 let (revoke_and_ack, commitment_signed, chan_monitor) = {
1902                         let mut channel_state = self.channel_state.lock().unwrap();
1903                         match channel_state.by_id.get_mut(&msg.channel_id) {
1904                                 Some(chan) => {
1905                                         if chan.get_their_node_id() != *their_node_id {
1906                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1907                                         }
1908                                         chan.commitment_signed(&msg)?
1909                                 },
1910                                 None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1911                         }
1912                 };
1913                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1914                         unimplemented!();
1915                 }
1916
1917                 Ok((revoke_and_ack, commitment_signed))
1918         }
1919
1920         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, HandleError> {
1921                 let (res, mut pending_forwards, mut pending_failures, chan_monitor) = {
1922                         let mut channel_state = self.channel_state.lock().unwrap();
1923                         match channel_state.by_id.get_mut(&msg.channel_id) {
1924                                 Some(chan) => {
1925                                         if chan.get_their_node_id() != *their_node_id {
1926                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1927                                         }
1928                                         chan.revoke_and_ack(&msg)?
1929                                 },
1930                                 None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1931                         }
1932                 };
1933                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1934                         unimplemented!();
1935                 }
1936                 for failure in pending_failures.drain(..) {
1937                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failure.0, failure.1);
1938                 }
1939
1940                 let mut forward_event = None;
1941                 if !pending_forwards.is_empty() {
1942                         let mut channel_state = self.channel_state.lock().unwrap();
1943                         if channel_state.forward_htlcs.is_empty() {
1944                                 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));
1945                                 channel_state.next_forward = forward_event.unwrap();
1946                         }
1947                         for forward_info in pending_forwards.drain(..) {
1948                                 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
1949                                         hash_map::Entry::Occupied(mut entry) => {
1950                                                 entry.get_mut().push(forward_info);
1951                                         },
1952                                         hash_map::Entry::Vacant(entry) => {
1953                                                 entry.insert(vec!(forward_info));
1954                                         }
1955                                 }
1956                         }
1957                 }
1958                 match forward_event {
1959                         Some(time) => {
1960                                 let mut pending_events = self.pending_events.lock().unwrap();
1961                                 pending_events.push(events::Event::PendingHTLCsForwardable {
1962                                         time_forwardable: time
1963                                 });
1964                         }
1965                         None => {},
1966                 }
1967
1968                 Ok(res)
1969         }
1970
1971         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
1972                 let mut channel_state = self.channel_state.lock().unwrap();
1973                 match channel_state.by_id.get_mut(&msg.channel_id) {
1974                         Some(chan) => {
1975                                 if chan.get_their_node_id() != *their_node_id {
1976                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1977                                 }
1978                                 chan.update_fee(&*self.fee_estimator, &msg)
1979                         },
1980                         None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
1981                 }
1982         }
1983
1984         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
1985                 let (chan_announcement, chan_update) = {
1986                         let mut channel_state = self.channel_state.lock().unwrap();
1987                         match channel_state.by_id.get_mut(&msg.channel_id) {
1988                                 Some(chan) => {
1989                                         if chan.get_their_node_id() != *their_node_id {
1990                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
1991                                         }
1992                                         if !chan.is_usable() {
1993                                                 return Err(HandleError{err: "Got an announcement_signatures before we were ready for it", action: None });
1994                                         }
1995
1996                                         let our_node_id = self.get_our_node_id();
1997                                         let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone())?;
1998
1999                                         let were_node_one = announcement.node_id_1 == our_node_id;
2000                                         let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2001                                         secp_call!(self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }));
2002                                         secp_call!(self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }));
2003
2004                                         let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2005
2006                                         (msgs::ChannelAnnouncement {
2007                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2008                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2009                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2010                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2011                                                 contents: announcement,
2012                                         }, self.get_channel_update(chan).unwrap()) // can only fail if we're not in a ready state
2013                                 },
2014                                 None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
2015                         }
2016                 };
2017                 let mut pending_events = self.pending_events.lock().unwrap();
2018                 pending_events.push(events::Event::BroadcastChannelAnnouncement { msg: chan_announcement, update_msg: chan_update });
2019                 Ok(())
2020         }
2021
2022         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2023                 let mut new_events = Vec::new();
2024                 let mut failed_channels = Vec::new();
2025                 {
2026                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2027                         let channel_state = channel_state_lock.borrow_parts();
2028                         let short_to_id = channel_state.short_to_id;
2029                         if no_connection_possible {
2030                                 channel_state.by_id.retain(|_, chan| {
2031                                         if chan.get_their_node_id() == *their_node_id {
2032                                                 if let Some(short_id) = chan.get_short_channel_id() {
2033                                                         short_to_id.remove(&short_id);
2034                                                 }
2035                                                 failed_channels.push(chan.force_shutdown());
2036                                                 if let Ok(update) = self.get_channel_update(&chan) {
2037                                                         new_events.push(events::Event::BroadcastChannelUpdate {
2038                                                                 msg: update
2039                                                         });
2040                                                 }
2041                                                 false
2042                                         } else {
2043                                                 true
2044                                         }
2045                                 });
2046                         } else {
2047                                 for chan in channel_state.by_id {
2048                                         if chan.1.get_their_node_id() == *their_node_id {
2049                                                 //TODO: mark channel disabled (and maybe announce such after a timeout). Also
2050                                                 //fail and wipe any uncommitted outbound HTLCs as those are considered after
2051                                                 //reconnect.
2052                                         }
2053                                 }
2054                         }
2055                 }
2056                 for failure in failed_channels.drain(..) {
2057                         self.finish_force_close_channel(failure);
2058                 }
2059                 if !new_events.is_empty() {
2060                         let mut pending_events = self.pending_events.lock().unwrap();
2061                         for event in new_events.drain(..) {
2062                                 pending_events.push(event);
2063                         }
2064                 }
2065         }
2066
2067         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2068                 if msg.channel_id == [0; 32] {
2069                         for chan in self.list_channels() {
2070                                 if chan.remote_network_id == *their_node_id {
2071                                         self.force_close_channel(&chan.channel_id);
2072                                 }
2073                         }
2074                 } else {
2075                         self.force_close_channel(&msg.channel_id);
2076                 }
2077         }
2078 }
2079
2080 #[cfg(test)]
2081 mod tests {
2082         use chain::chaininterface;
2083         use chain::transaction::OutPoint;
2084         use chain::chaininterface::ChainListener;
2085         use ln::channelmanager::{ChannelManager,OnionKeys};
2086         use ln::router::{Route, RouteHop, Router};
2087         use ln::msgs;
2088         use ln::msgs::{MsgEncodable,ChannelMessageHandler,RoutingMessageHandler};
2089         use util::test_utils;
2090         use util::events::{Event, EventsProvider};
2091         use util::logger::Logger;
2092
2093         use bitcoin::util::hash::Sha256dHash;
2094         use bitcoin::blockdata::block::{Block, BlockHeader};
2095         use bitcoin::blockdata::transaction::{Transaction, TxOut};
2096         use bitcoin::network::constants::Network;
2097         use bitcoin::network::serialize::serialize;
2098         use bitcoin::network::serialize::BitcoinHash;
2099
2100         use hex;
2101
2102         use secp256k1::Secp256k1;
2103         use secp256k1::key::{PublicKey,SecretKey};
2104
2105         use crypto::sha2::Sha256;
2106         use crypto::digest::Digest;
2107
2108         use rand::{thread_rng,Rng};
2109
2110         use std::collections::HashMap;
2111         use std::default::Default;
2112         use std::sync::{Arc, Mutex};
2113         use std::time::Instant;
2114         use std::mem;
2115
2116         fn build_test_onion_keys() -> Vec<OnionKeys> {
2117                 // Keys from BOLT 4, used in both test vector tests
2118                 let secp_ctx = Secp256k1::new();
2119
2120                 let route = Route {
2121                         hops: vec!(
2122                                         RouteHop {
2123                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
2124                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2125                                         },
2126                                         RouteHop {
2127                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
2128                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2129                                         },
2130                                         RouteHop {
2131                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
2132                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2133                                         },
2134                                         RouteHop {
2135                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
2136                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2137                                         },
2138                                         RouteHop {
2139                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
2140                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2141                                         },
2142                         ),
2143                 };
2144
2145                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
2146
2147                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2148                 assert_eq!(onion_keys.len(), route.hops.len());
2149                 onion_keys
2150         }
2151
2152         #[test]
2153         fn onion_vectors() {
2154                 // Packet creation test vectors from BOLT 4
2155                 let onion_keys = build_test_onion_keys();
2156
2157                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
2158                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
2159                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
2160                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
2161                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
2162
2163                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
2164                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
2165                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
2166                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
2167                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
2168
2169                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
2170                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
2171                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
2172                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
2173                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
2174
2175                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
2176                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
2177                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
2178                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
2179                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
2180
2181                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
2182                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
2183                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
2184                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
2185                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
2186
2187                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
2188                 let payloads = vec!(
2189                         msgs::OnionHopData {
2190                                 realm: 0,
2191                                 data: msgs::OnionRealm0HopData {
2192                                         short_channel_id: 0,
2193                                         amt_to_forward: 0,
2194                                         outgoing_cltv_value: 0,
2195                                 },
2196                                 hmac: [0; 32],
2197                         },
2198                         msgs::OnionHopData {
2199                                 realm: 0,
2200                                 data: msgs::OnionRealm0HopData {
2201                                         short_channel_id: 0x0101010101010101,
2202                                         amt_to_forward: 0x0100000001,
2203                                         outgoing_cltv_value: 0,
2204                                 },
2205                                 hmac: [0; 32],
2206                         },
2207                         msgs::OnionHopData {
2208                                 realm: 0,
2209                                 data: msgs::OnionRealm0HopData {
2210                                         short_channel_id: 0x0202020202020202,
2211                                         amt_to_forward: 0x0200000002,
2212                                         outgoing_cltv_value: 0,
2213                                 },
2214                                 hmac: [0; 32],
2215                         },
2216                         msgs::OnionHopData {
2217                                 realm: 0,
2218                                 data: msgs::OnionRealm0HopData {
2219                                         short_channel_id: 0x0303030303030303,
2220                                         amt_to_forward: 0x0300000003,
2221                                         outgoing_cltv_value: 0,
2222                                 },
2223                                 hmac: [0; 32],
2224                         },
2225                         msgs::OnionHopData {
2226                                 realm: 0,
2227                                 data: msgs::OnionRealm0HopData {
2228                                         short_channel_id: 0x0404040404040404,
2229                                         amt_to_forward: 0x0400000004,
2230                                         outgoing_cltv_value: 0,
2231                                 },
2232                                 hmac: [0; 32],
2233                         },
2234                 );
2235
2236                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]).unwrap();
2237                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
2238                 // anyway...
2239                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
2240         }
2241
2242         #[test]
2243         fn test_failure_packet_onion() {
2244                 // Returning Errors test vectors from BOLT 4
2245
2246                 let onion_keys = build_test_onion_keys();
2247                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret, 0x2002, &[0; 0]);
2248                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
2249
2250                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret, &onion_error.encode()[..]);
2251                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
2252
2253                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret, &onion_packet_1.data[..]);
2254                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
2255
2256                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret, &onion_packet_2.data[..]);
2257                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
2258
2259                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret, &onion_packet_3.data[..]);
2260                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
2261
2262                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret, &onion_packet_4.data[..]);
2263                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
2264         }
2265
2266         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
2267                 assert!(chain.does_match_tx(tx));
2268                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2269                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
2270                 for i in 2..100 {
2271                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2272                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
2273                 }
2274         }
2275
2276         struct Node {
2277                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
2278                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
2279                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
2280                 node: Arc<ChannelManager>,
2281                 router: Router,
2282         }
2283
2284         static mut CHAN_COUNT: u32 = 0;
2285         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2286                 node_a.node.create_channel(node_b.node.get_our_node_id(), 100000, 10001, 42).unwrap();
2287
2288                 let events_1 = node_a.node.get_and_clear_pending_events();
2289                 assert_eq!(events_1.len(), 1);
2290                 let accept_chan = match events_1[0] {
2291                         Event::SendOpenChannel { ref node_id, ref msg } => {
2292                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2293                                 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), msg).unwrap()
2294                         },
2295                         _ => panic!("Unexpected event"),
2296                 };
2297
2298                 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_chan).unwrap();
2299
2300                 let chan_id = unsafe { CHAN_COUNT };
2301                 let tx;
2302                 let funding_output;
2303
2304                 let events_2 = node_a.node.get_and_clear_pending_events();
2305                 assert_eq!(events_2.len(), 1);
2306                 match events_2[0] {
2307                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
2308                                 assert_eq!(*channel_value_satoshis, 100000);
2309                                 assert_eq!(user_channel_id, 42);
2310
2311                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
2312                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
2313                                 }]};
2314                                 funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
2315
2316                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
2317                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2318                                 assert_eq!(added_monitors.len(), 1);
2319                                 assert_eq!(added_monitors[0].0, funding_output);
2320                                 added_monitors.clear();
2321                         },
2322                         _ => panic!("Unexpected event"),
2323                 }
2324
2325                 let events_3 = node_a.node.get_and_clear_pending_events();
2326                 assert_eq!(events_3.len(), 1);
2327                 let funding_signed = match events_3[0] {
2328                         Event::SendFundingCreated { ref node_id, ref msg } => {
2329                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2330                                 let res = node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), msg).unwrap();
2331                                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
2332                                 assert_eq!(added_monitors.len(), 1);
2333                                 assert_eq!(added_monitors[0].0, funding_output);
2334                                 added_monitors.clear();
2335                                 res
2336                         },
2337                         _ => panic!("Unexpected event"),
2338                 };
2339
2340                 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &funding_signed).unwrap();
2341                 {
2342                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2343                         assert_eq!(added_monitors.len(), 1);
2344                         assert_eq!(added_monitors[0].0, funding_output);
2345                         added_monitors.clear();
2346                 }
2347
2348                 let events_4 = node_a.node.get_and_clear_pending_events();
2349                 assert_eq!(events_4.len(), 1);
2350                 match events_4[0] {
2351                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
2352                                 assert_eq!(user_channel_id, 42);
2353                                 assert_eq!(*funding_txo, funding_output);
2354                         },
2355                         _ => panic!("Unexpected event"),
2356                 };
2357
2358                 confirm_transaction(&node_a.chain_monitor, &tx, chan_id);
2359                 let events_5 = node_a.node.get_and_clear_pending_events();
2360                 assert_eq!(events_5.len(), 1);
2361                 match events_5[0] {
2362                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2363                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2364                                 assert!(announcement_sigs.is_none());
2365                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), msg).unwrap()
2366                         },
2367                         _ => panic!("Unexpected event"),
2368                 };
2369
2370                 let channel_id;
2371
2372                 confirm_transaction(&node_b.chain_monitor, &tx, chan_id);
2373                 let events_6 = node_b.node.get_and_clear_pending_events();
2374                 assert_eq!(events_6.len(), 1);
2375                 let as_announcement_sigs = match events_6[0] {
2376                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2377                                 assert_eq!(*node_id, node_a.node.get_our_node_id());
2378                                 channel_id = msg.channel_id.clone();
2379                                 let as_announcement_sigs = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), msg).unwrap().unwrap();
2380                                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &(*announcement_sigs).clone().unwrap()).unwrap();
2381                                 as_announcement_sigs
2382                         },
2383                         _ => panic!("Unexpected event"),
2384                 };
2385
2386                 let events_7 = node_a.node.get_and_clear_pending_events();
2387                 assert_eq!(events_7.len(), 1);
2388                 let (announcement, as_update) = match events_7[0] {
2389                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2390                                 (msg, update_msg)
2391                         },
2392                         _ => panic!("Unexpected event"),
2393                 };
2394
2395                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_announcement_sigs).unwrap();
2396                 let events_8 = node_b.node.get_and_clear_pending_events();
2397                 assert_eq!(events_8.len(), 1);
2398                 let bs_update = match events_8[0] {
2399                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2400                                 assert!(*announcement == *msg);
2401                                 update_msg
2402                         },
2403                         _ => panic!("Unexpected event"),
2404                 };
2405
2406                 unsafe {
2407                         CHAN_COUNT += 1;
2408                 }
2409
2410                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone(), channel_id, tx)
2411         }
2412
2413         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2414                 let chan_announcement = create_chan_between_nodes(&nodes[a], &nodes[b]);
2415                 for node in nodes {
2416                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
2417                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
2418                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
2419                 }
2420                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
2421         }
2422
2423         fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate) {
2424                 let (node_a, broadcaster_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster) } else { (&outbound_node.node, &outbound_node.tx_broadcaster) };
2425                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
2426                 let (tx_a, tx_b);
2427
2428                 node_a.close_channel(channel_id).unwrap();
2429                 let events_1 = node_a.get_and_clear_pending_events();
2430                 assert_eq!(events_1.len(), 1);
2431                 let shutdown_a = match events_1[0] {
2432                         Event::SendShutdown { ref node_id, ref msg } => {
2433                                 assert_eq!(node_id, &node_b.get_our_node_id());
2434                                 msg.clone()
2435                         },
2436                         _ => panic!("Unexpected event"),
2437                 };
2438
2439                 let (shutdown_b, mut closing_signed_b) = node_b.handle_shutdown(&node_a.get_our_node_id(), &shutdown_a).unwrap();
2440                 if !close_inbound_first {
2441                         assert!(closing_signed_b.is_none());
2442                 }
2443                 let (empty_a, mut closing_signed_a) = node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b.unwrap()).unwrap();
2444                 assert!(empty_a.is_none());
2445                 if close_inbound_first {
2446                         assert!(closing_signed_a.is_none());
2447                         closing_signed_a = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2448                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2449                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2450
2451                         let empty_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2452                         assert!(empty_b.is_none());
2453                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2454                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2455                 } else {
2456                         closing_signed_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2457                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2458                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2459
2460                         let empty_a2 = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2461                         assert!(empty_a2.is_none());
2462                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2463                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2464                 }
2465                 assert_eq!(tx_a, tx_b);
2466                 let mut funding_tx_map = HashMap::new();
2467                 funding_tx_map.insert(funding_tx.txid(), funding_tx);
2468                 tx_a.verify(&funding_tx_map).unwrap();
2469
2470                 let events_2 = node_a.get_and_clear_pending_events();
2471                 assert_eq!(events_2.len(), 1);
2472                 let as_update = match events_2[0] {
2473                         Event::BroadcastChannelUpdate { ref msg } => {
2474                                 msg.clone()
2475                         },
2476                         _ => panic!("Unexpected event"),
2477                 };
2478
2479                 let events_3 = node_b.get_and_clear_pending_events();
2480                 assert_eq!(events_3.len(), 1);
2481                 let bs_update = match events_3[0] {
2482                         Event::BroadcastChannelUpdate { ref msg } => {
2483                                 msg.clone()
2484                         },
2485                         _ => panic!("Unexpected event"),
2486                 };
2487
2488                 (as_update, bs_update)
2489         }
2490
2491         struct SendEvent {
2492                 node_id: PublicKey,
2493                 msgs: Vec<msgs::UpdateAddHTLC>,
2494                 commitment_msg: msgs::CommitmentSigned,
2495         }
2496         impl SendEvent {
2497                 fn from_event(event: Event) -> SendEvent {
2498                         match event {
2499                                 Event::UpdateHTLCs { node_id, updates: msgs::CommitmentUpdate { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs, commitment_signed } } => {
2500                                         assert!(update_fulfill_htlcs.is_empty());
2501                                         assert!(update_fail_htlcs.is_empty());
2502                                         assert!(update_fail_malformed_htlcs.is_empty());
2503                                         SendEvent { node_id: node_id, msgs: update_add_htlcs, commitment_msg: commitment_signed }
2504                                 },
2505                                 _ => panic!("Unexpected event type!"),
2506                         }
2507                 }
2508         }
2509
2510         static mut PAYMENT_COUNT: u8 = 0;
2511         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2512                 let our_payment_preimage = unsafe { [PAYMENT_COUNT; 32] };
2513                 unsafe { PAYMENT_COUNT += 1 };
2514                 let our_payment_hash = {
2515                         let mut sha = Sha256::new();
2516                         sha.input(&our_payment_preimage[..]);
2517                         let mut ret = [0; 32];
2518                         sha.result(&mut ret);
2519                         ret
2520                 };
2521
2522                 let mut payment_event = {
2523                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
2524                         {
2525                                 let mut added_monitors = origin_node.chan_monitor.added_monitors.lock().unwrap();
2526                                 assert_eq!(added_monitors.len(), 1);
2527                                 added_monitors.clear();
2528                         }
2529
2530                         let mut events = origin_node.node.get_and_clear_pending_events();
2531                         assert_eq!(events.len(), 1);
2532                         SendEvent::from_event(events.remove(0))
2533                 };
2534                 let mut prev_node = origin_node;
2535
2536                 for (idx, &node) in expected_route.iter().enumerate() {
2537                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
2538
2539                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2540                         {
2541                                 let added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2542                                 assert_eq!(added_monitors.len(), 0);
2543                         }
2544
2545                         let revoke_and_ack = node.node.handle_commitment_signed(&prev_node.node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2546                         {
2547                                 let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2548                                 assert_eq!(added_monitors.len(), 1);
2549                                 added_monitors.clear();
2550                         }
2551                         assert!(prev_node.node.handle_revoke_and_ack(&node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2552                         let prev_revoke_and_ack = prev_node.node.handle_commitment_signed(&node.node.get_our_node_id(), &revoke_and_ack.1.unwrap()).unwrap();
2553                         {
2554                                 let mut added_monitors = prev_node.chan_monitor.added_monitors.lock().unwrap();
2555                                 assert_eq!(added_monitors.len(), 2);
2556                                 added_monitors.clear();
2557                         }
2558                         assert!(node.node.handle_revoke_and_ack(&prev_node.node.get_our_node_id(), &prev_revoke_and_ack.0).unwrap().is_none());
2559                         assert!(prev_revoke_and_ack.1.is_none());
2560                         {
2561                                 let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2562                                 assert_eq!(added_monitors.len(), 1);
2563                                 added_monitors.clear();
2564                         }
2565
2566                         let events_1 = node.node.get_and_clear_pending_events();
2567                         assert_eq!(events_1.len(), 1);
2568                         match events_1[0] {
2569                                 Event::PendingHTLCsForwardable { .. } => { },
2570                                 _ => panic!("Unexpected event"),
2571                         };
2572
2573                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
2574                         node.node.process_pending_htlc_forwards();
2575
2576                         let mut events_2 = node.node.get_and_clear_pending_events();
2577                         assert_eq!(events_2.len(), 1);
2578                         if idx == expected_route.len() - 1 {
2579                                 match events_2[0] {
2580                                         Event::PaymentReceived { ref payment_hash, amt } => {
2581                                                 assert_eq!(our_payment_hash, *payment_hash);
2582                                                 assert_eq!(amt, recv_value);
2583                                         },
2584                                         _ => panic!("Unexpected event"),
2585                                 }
2586                         } else {
2587                                 {
2588                                         let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2589                                         assert_eq!(added_monitors.len(), 1);
2590                                         added_monitors.clear();
2591                                 }
2592                                 payment_event = SendEvent::from_event(events_2.remove(0));
2593                                 assert_eq!(payment_event.msgs.len(), 1);
2594                         }
2595
2596                         prev_node = node;
2597                 }
2598
2599                 (our_payment_preimage, our_payment_hash)
2600         }
2601
2602         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
2603                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
2604                 {
2605                         let mut added_monitors = expected_route.last().unwrap().chan_monitor.added_monitors.lock().unwrap();
2606                         assert_eq!(added_monitors.len(), 1);
2607                         added_monitors.clear();
2608                 }
2609
2610                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
2611                 macro_rules! update_fulfill_dance {
2612                         ($node: expr, $prev_node: expr, $last_node: expr) => {
2613                                 {
2614                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2615                                         {
2616                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2617                                                 if $last_node {
2618                                                         assert_eq!(added_monitors.len(), 0);
2619                                                 } else {
2620                                                         assert_eq!(added_monitors.len(), 1);
2621                                                 }
2622                                                 added_monitors.clear();
2623                                         }
2624                                         let revoke_and_commit = $node.node.handle_commitment_signed(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().1).unwrap();
2625                                         {
2626                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2627                                                 assert_eq!(added_monitors.len(), 1);
2628                                                 added_monitors.clear();
2629                                         }
2630                                         assert!($prev_node.node.handle_revoke_and_ack(&$node.node.get_our_node_id(), &revoke_and_commit.0).unwrap().is_none());
2631                                         let revoke_and_ack = $prev_node.node.handle_commitment_signed(&$node.node.get_our_node_id(), &revoke_and_commit.1.unwrap()).unwrap();
2632                                         assert!(revoke_and_ack.1.is_none());
2633                                         {
2634                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2635                                                 assert_eq!(added_monitors.len(), 2);
2636                                                 added_monitors.clear();
2637                                         }
2638                                         assert!($node.node.handle_revoke_and_ack(&$prev_node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2639                                         {
2640                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2641                                                 assert_eq!(added_monitors.len(), 1);
2642                                                 added_monitors.clear();
2643                                         }
2644                                 }
2645                         }
2646                 }
2647
2648                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2649                 let mut prev_node = expected_route.last().unwrap();
2650                 for node in expected_route.iter().rev() {
2651                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2652                         if next_msgs.is_some() {
2653                                 update_fulfill_dance!(node, prev_node, false);
2654                         }
2655
2656                         let events = node.node.get_and_clear_pending_events();
2657                         assert_eq!(events.len(), 1);
2658                         match events[0] {
2659                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed } } => {
2660                                         assert!(update_add_htlcs.is_empty());
2661                                         assert_eq!(update_fulfill_htlcs.len(), 1);
2662                                         assert!(update_fail_htlcs.is_empty());
2663                                         assert!(update_fail_malformed_htlcs.is_empty());
2664                                         expected_next_node = node_id.clone();
2665                                         next_msgs = Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()));
2666                                 },
2667                                 _ => panic!("Unexpected event"),
2668                         };
2669
2670                         prev_node = node;
2671                 }
2672
2673                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2674                 update_fulfill_dance!(origin_node, expected_route.first().unwrap(), true);
2675
2676                 let events = origin_node.node.get_and_clear_pending_events();
2677                 assert_eq!(events.len(), 1);
2678                 match events[0] {
2679                         Event::PaymentSent { payment_preimage } => {
2680                                 assert_eq!(payment_preimage, our_payment_preimage);
2681                         },
2682                         _ => panic!("Unexpected event"),
2683                 }
2684         }
2685
2686         const TEST_FINAL_CLTV: u32 = 32;
2687
2688         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2689                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
2690                 assert_eq!(route.hops.len(), expected_route.len());
2691                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2692                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
2693                 }
2694
2695                 send_along_route(origin_node, route, expected_route, recv_value)
2696         }
2697
2698         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
2699                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
2700                 assert_eq!(route.hops.len(), expected_route.len());
2701                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2702                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
2703                 }
2704
2705                 let our_payment_preimage = unsafe { [PAYMENT_COUNT; 32] };
2706                 unsafe { PAYMENT_COUNT += 1 };
2707                 let our_payment_hash = {
2708                         let mut sha = Sha256::new();
2709                         sha.input(&our_payment_preimage[..]);
2710                         let mut ret = [0; 32];
2711                         sha.result(&mut ret);
2712                         ret
2713                 };
2714
2715                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
2716                 assert_eq!(err.err, "Cannot send value that would put us over our max HTLC value in flight");
2717         }
2718
2719         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
2720                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
2721                 claim_payment(&origin, expected_route, our_payment_preimage);
2722         }
2723
2724         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
2725                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
2726                 {
2727                         let mut added_monitors = expected_route.last().unwrap().chan_monitor.added_monitors.lock().unwrap();
2728                         assert_eq!(added_monitors.len(), 1);
2729                         added_monitors.clear();
2730                 }
2731
2732                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
2733                 macro_rules! update_fail_dance {
2734                         ($node: expr, $prev_node: expr, $last_node: expr) => {
2735                                 {
2736                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2737                                         let revoke_and_commit = $node.node.handle_commitment_signed(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().1).unwrap();
2738
2739                                         {
2740                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2741                                                 assert_eq!(added_monitors.len(), 1);
2742                                                 added_monitors.clear();
2743                                         }
2744                                         assert!($prev_node.node.handle_revoke_and_ack(&$node.node.get_our_node_id(), &revoke_and_commit.0).unwrap().is_none());
2745                                         {
2746                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2747                                                 assert_eq!(added_monitors.len(), 1);
2748                                                 added_monitors.clear();
2749                                         }
2750                                         let revoke_and_ack = $prev_node.node.handle_commitment_signed(&$node.node.get_our_node_id(), &revoke_and_commit.1.unwrap()).unwrap();
2751                                         {
2752                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2753                                                 assert_eq!(added_monitors.len(), 1);
2754                                                 added_monitors.clear();
2755                                         }
2756                                         assert!(revoke_and_ack.1.is_none());
2757                                         assert!($node.node.get_and_clear_pending_events().is_empty());
2758                                         assert!($node.node.handle_revoke_and_ack(&$prev_node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2759                                         {
2760                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2761                                                 if $last_node {
2762                                                         assert_eq!(added_monitors.len(), 1);
2763                                                 } else {
2764                                                         assert_eq!(added_monitors.len(), 2);
2765                                                         assert!(added_monitors[0].0 != added_monitors[1].0);
2766                                                 }
2767                                                 added_monitors.clear();
2768                                         }
2769                                 }
2770                         }
2771                 }
2772
2773                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2774                 let mut prev_node = expected_route.last().unwrap();
2775                 for node in expected_route.iter().rev() {
2776                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2777                         if next_msgs.is_some() {
2778                                 update_fail_dance!(node, prev_node, false);
2779                         }
2780
2781                         let events = node.node.get_and_clear_pending_events();
2782                         assert_eq!(events.len(), 1);
2783                         match events[0] {
2784                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed } } => {
2785                                         assert!(update_add_htlcs.is_empty());
2786                                         assert!(update_fulfill_htlcs.is_empty());
2787                                         assert_eq!(update_fail_htlcs.len(), 1);
2788                                         assert!(update_fail_malformed_htlcs.is_empty());
2789                                         expected_next_node = node_id.clone();
2790                                         next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
2791                                 },
2792                                 _ => panic!("Unexpected event"),
2793                         };
2794
2795                         prev_node = node;
2796                 }
2797
2798                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2799                 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
2800
2801                 let events = origin_node.node.get_and_clear_pending_events();
2802                 assert_eq!(events.len(), 1);
2803                 match events[0] {
2804                         Event::PaymentFailed { payment_hash } => {
2805                                 assert_eq!(payment_hash, our_payment_hash);
2806                         },
2807                         _ => panic!("Unexpected event"),
2808                 }
2809         }
2810
2811         fn create_network(node_count: usize) -> Vec<Node> {
2812                 let mut nodes = Vec::new();
2813                 let mut rng = thread_rng();
2814                 let secp_ctx = Secp256k1::new();
2815                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
2816
2817                 for _ in 0..node_count {
2818                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
2819                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
2820                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
2821                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
2822                         let node_id = {
2823                                 let mut key_slice = [0; 32];
2824                                 rng.fill_bytes(&mut key_slice);
2825                                 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
2826                         };
2827                         let node = ChannelManager::new(node_id.clone(), 0, true, Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger)).unwrap();
2828                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
2829                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router });
2830                 }
2831
2832                 nodes
2833         }
2834
2835         #[test]
2836         fn fake_network_test() {
2837                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2838                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
2839                 let nodes = create_network(4);
2840
2841                 // Create some initial channels
2842                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2843                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2844                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2845
2846                 // Rebalance the network a bit by relaying one payment through all the channels...
2847                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2848                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2849                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2850                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2851
2852                 // Send some more payments
2853                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
2854                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
2855                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
2856
2857                 // Test failure packets
2858                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
2859                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
2860
2861                 // Add a new channel that skips 3
2862                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
2863
2864                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
2865                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
2866                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2867                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2868                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2869                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2870                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2871
2872                 // Do some rebalance loop payments, simultaneously
2873                 let mut hops = Vec::with_capacity(3);
2874                 hops.push(RouteHop {
2875                         pubkey: nodes[2].node.get_our_node_id(),
2876                         short_channel_id: chan_2.0.contents.short_channel_id,
2877                         fee_msat: 0,
2878                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
2879                 });
2880                 hops.push(RouteHop {
2881                         pubkey: nodes[3].node.get_our_node_id(),
2882                         short_channel_id: chan_3.0.contents.short_channel_id,
2883                         fee_msat: 0,
2884                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
2885                 });
2886                 hops.push(RouteHop {
2887                         pubkey: nodes[1].node.get_our_node_id(),
2888                         short_channel_id: chan_4.0.contents.short_channel_id,
2889                         fee_msat: 1000000,
2890                         cltv_expiry_delta: TEST_FINAL_CLTV,
2891                 });
2892                 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
2893                 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
2894                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
2895
2896                 let mut hops = Vec::with_capacity(3);
2897                 hops.push(RouteHop {
2898                         pubkey: nodes[3].node.get_our_node_id(),
2899                         short_channel_id: chan_4.0.contents.short_channel_id,
2900                         fee_msat: 0,
2901                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
2902                 });
2903                 hops.push(RouteHop {
2904                         pubkey: nodes[2].node.get_our_node_id(),
2905                         short_channel_id: chan_3.0.contents.short_channel_id,
2906                         fee_msat: 0,
2907                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
2908                 });
2909                 hops.push(RouteHop {
2910                         pubkey: nodes[1].node.get_our_node_id(),
2911                         short_channel_id: chan_2.0.contents.short_channel_id,
2912                         fee_msat: 1000000,
2913                         cltv_expiry_delta: TEST_FINAL_CLTV,
2914                 });
2915                 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
2916                 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
2917                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
2918
2919                 // Claim the rebalances...
2920                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
2921                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
2922
2923                 // Add a duplicate new channel from 2 to 4
2924                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
2925
2926                 // Send some payments across both channels
2927                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
2928                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
2929                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
2930
2931                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
2932
2933                 //TODO: Test that routes work again here as we've been notified that the channel is full
2934
2935                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
2936                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
2937                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
2938
2939                 // Close down the channels...
2940                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
2941                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
2942                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
2943                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
2944                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
2945
2946                 // Check that we processed all pending events
2947                 for node in nodes {
2948                         assert_eq!(node.node.get_and_clear_pending_events().len(), 0);
2949                         assert_eq!(node.chan_monitor.added_monitors.lock().unwrap().len(), 0);
2950                 }
2951         }
2952
2953         #[derive(PartialEq)]
2954         enum HTLCType { NONE, TIMEOUT, SUCCESS }
2955         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
2956                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2957                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
2958
2959                 let mut res = Vec::with_capacity(2);
2960
2961                 if let Some(explicit_tx) = commitment_tx {
2962                         res.push(explicit_tx.clone());
2963                 } else {
2964                         for tx in node_txn.iter() {
2965                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
2966                                         let mut funding_tx_map = HashMap::new();
2967                                         funding_tx_map.insert(chan.3.txid(), chan.3.clone());
2968                                         tx.verify(&funding_tx_map).unwrap();
2969                                         res.push(tx.clone());
2970                                 }
2971                         }
2972                 }
2973                 assert_eq!(res.len(), 1);
2974
2975                 if has_htlc_tx != HTLCType::NONE {
2976                         for tx in node_txn.iter() {
2977                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2978                                         let mut funding_tx_map = HashMap::new();
2979                                         funding_tx_map.insert(res[0].txid(), res[0].clone());
2980                                         tx.verify(&funding_tx_map).unwrap();
2981                                         if has_htlc_tx == HTLCType::TIMEOUT {
2982                                                 assert!(tx.lock_time != 0);
2983                                         } else {
2984                                                 assert!(tx.lock_time == 0);
2985                                         }
2986                                         res.push(tx.clone());
2987                                         break;
2988                                 }
2989                         }
2990                         assert_eq!(res.len(), 2);
2991                 }
2992                 node_txn.clear();
2993                 res
2994         }
2995
2996         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
2997                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2998
2999                 assert!(node_txn.len() >= 1);
3000                 assert_eq!(node_txn[0].input.len(), 1);
3001                 let mut found_prev = false;
3002
3003                 for tx in prev_txn {
3004                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
3005                                 let mut funding_tx_map = HashMap::new();
3006                                 funding_tx_map.insert(tx.txid(), tx.clone());
3007                                 node_txn[0].verify(&funding_tx_map).unwrap();
3008
3009                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
3010                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
3011
3012                                 found_prev = true;
3013                                 break;
3014                         }
3015                 }
3016                 assert!(found_prev);
3017
3018                 let mut res = Vec::new();
3019                 mem::swap(&mut *node_txn, &mut res);
3020                 res
3021         }
3022
3023         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
3024                 let events_1 = nodes[a].node.get_and_clear_pending_events();
3025                 assert_eq!(events_1.len(), 1);
3026                 let as_update = match events_1[0] {
3027                         Event::BroadcastChannelUpdate { ref msg } => {
3028                                 msg.clone()
3029                         },
3030                         _ => panic!("Unexpected event"),
3031                 };
3032
3033                 let events_2 = nodes[b].node.get_and_clear_pending_events();
3034                 assert_eq!(events_2.len(), 1);
3035                 let bs_update = match events_2[0] {
3036                         Event::BroadcastChannelUpdate { ref msg } => {
3037                                 msg.clone()
3038                         },
3039                         _ => panic!("Unexpected event"),
3040                 };
3041
3042                 for node in nodes {
3043                         node.router.handle_channel_update(&as_update).unwrap();
3044                         node.router.handle_channel_update(&bs_update).unwrap();
3045                 }
3046         }
3047
3048         #[test]
3049         fn channel_monitor_network_test() {
3050                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
3051                 // tests that ChannelMonitor is able to recover from various states.
3052                 let nodes = create_network(5);
3053
3054                 // Create some initial channels
3055                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3056                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3057                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
3058                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
3059
3060                 // Rebalance the network a bit by relaying one payment through all the channels...
3061                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3062                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3063                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3064                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3065
3066                 // Simple case with no pending HTLCs:
3067                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
3068                 {
3069                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
3070                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3071                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
3072                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
3073                 }
3074                 get_announce_close_broadcast_events(&nodes, 0, 1);
3075                 assert_eq!(nodes[0].node.list_channels().len(), 0);
3076                 assert_eq!(nodes[1].node.list_channels().len(), 1);
3077
3078                 // One pending HTLC is discarded by the force-close:
3079                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
3080
3081                 // Simple case of one pending HTLC to HTLC-Timeout
3082                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
3083                 {
3084                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
3085                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3086                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
3087                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
3088                 }
3089                 get_announce_close_broadcast_events(&nodes, 1, 2);
3090                 assert_eq!(nodes[1].node.list_channels().len(), 0);
3091                 assert_eq!(nodes[2].node.list_channels().len(), 1);
3092
3093                 macro_rules! claim_funds {
3094                         ($node: expr, $prev_node: expr, $preimage: expr) => {
3095                                 {
3096                                         assert!($node.node.claim_funds($preimage));
3097                                         {
3098                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3099                                                 assert_eq!(added_monitors.len(), 1);
3100                                                 added_monitors.clear();
3101                                         }
3102
3103                                         let events = $node.node.get_and_clear_pending_events();
3104                                         assert_eq!(events.len(), 1);
3105                                         match events[0] {
3106                                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
3107                                                         assert!(update_add_htlcs.is_empty());
3108                                                         assert!(update_fail_htlcs.is_empty());
3109                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
3110                                                 },
3111                                                 _ => panic!("Unexpected event"),
3112                                         };
3113                                 }
3114                         }
3115                 }
3116
3117                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
3118                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
3119                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
3120                 {
3121                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
3122
3123                         // Claim the payment on nodes[3], giving it knowledge of the preimage
3124                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
3125
3126                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3127                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
3128
3129                         check_preimage_claim(&nodes[3], &node_txn);
3130                 }
3131                 get_announce_close_broadcast_events(&nodes, 2, 3);
3132                 assert_eq!(nodes[2].node.list_channels().len(), 0);
3133                 assert_eq!(nodes[3].node.list_channels().len(), 1);
3134
3135                 // One pending HTLC to time out:
3136                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
3137
3138                 {
3139                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3140                         nodes[3].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
3141                         for i in 2..TEST_FINAL_CLTV - 3 {
3142                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3143                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
3144                         }
3145
3146                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
3147
3148                         // Claim the payment on nodes[3], giving it knowledge of the preimage
3149                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
3150
3151                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3152                         nodes[4].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
3153                         for i in 2..TEST_FINAL_CLTV - 3 {
3154                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3155                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
3156                         }
3157
3158                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
3159
3160                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3161                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
3162
3163                         check_preimage_claim(&nodes[4], &node_txn);
3164                 }
3165                 get_announce_close_broadcast_events(&nodes, 3, 4);
3166                 assert_eq!(nodes[3].node.list_channels().len(), 0);
3167                 assert_eq!(nodes[4].node.list_channels().len(), 0);
3168
3169                 // Create some new channels:
3170                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
3171
3172                 // A pending HTLC which will be revoked:
3173                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3174                 // Get the will-be-revoked local txn from nodes[0]
3175                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3176                 // Revoke the old state
3177                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
3178
3179                 {
3180                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3181                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3182                         {
3183                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3184                                 assert_eq!(node_txn.len(), 2);
3185                                 assert_eq!(node_txn[0].input.len(), 1);
3186
3187                                 let mut funding_tx_map = HashMap::new();
3188                                 funding_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
3189                                 node_txn[0].verify(&funding_tx_map).unwrap();
3190                                 node_txn.swap_remove(0);
3191                         }
3192                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
3193
3194                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3195                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
3196                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3197                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
3198
3199                         //TODO: At this point nodes[1] should claim the revoked HTLC-Timeout output, but that's
3200                         //not yet implemented in ChannelMonitor
3201                 }
3202                 get_announce_close_broadcast_events(&nodes, 0, 1);
3203                 assert_eq!(nodes[0].node.list_channels().len(), 0);
3204                 assert_eq!(nodes[1].node.list_channels().len(), 0);
3205
3206                 // Check that we processed all pending events
3207                 for node in nodes {
3208                         assert_eq!(node.node.get_and_clear_pending_events().len(), 0);
3209                         assert_eq!(node.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3210                 }
3211         }
3212
3213         #[test]
3214         fn test_unconf_chan() {
3215                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3216                 let nodes = create_network(2);
3217                 create_announced_chan_between_nodes(&nodes, 0, 1);
3218
3219                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3220                 assert_eq!(channel_state.by_id.len(), 1);
3221                 assert_eq!(channel_state.short_to_id.len(), 1);
3222                 mem::drop(channel_state);
3223
3224                 let mut headers = Vec::new();
3225                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3226                 headers.push(header.clone());
3227                 for _i in 2..100 {
3228                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3229                         headers.push(header.clone());
3230                 }
3231                 while !headers.is_empty() {
3232                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
3233                 }
3234                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3235                 assert_eq!(channel_state.by_id.len(), 0);
3236                 assert_eq!(channel_state.short_to_id.len(), 0);
3237         }
3238 }