1 //! The top-level channel management and payment tracking stuff lives here.
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::network::serialize::BitcoinHash;
16 use bitcoin::util::hash::Sha256dHash;
18 use secp256k1::key::{SecretKey,PublicKey};
19 use secp256k1::{Secp256k1,Message};
20 use secp256k1::ecdh::SharedSecret;
23 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
24 use chain::transaction::OutPoint;
25 use ln::channel::{Channel, ChannelError, ChannelKeys};
26 use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
27 use ln::router::{Route,RouteHop};
29 use ln::msgs::{HandleError,ChannelMessageHandler};
30 use util::{byte_utils, events, internal_traits, rng};
31 use util::sha2::Sha256;
32 use util::ser::{Readable, Writeable};
33 use util::chacha20poly1305rfc::ChaCha20;
34 use util::logger::Logger;
35 use util::errors::APIError;
38 use crypto::mac::{Mac,MacResult};
39 use crypto::hmac::Hmac;
40 use crypto::digest::Digest;
41 use crypto::symmetriccipher::SynchronousStreamCipher;
44 use std::collections::HashMap;
45 use std::collections::hash_map;
47 use std::sync::{Mutex,MutexGuard,Arc};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
65 use ln::router::Route;
66 use secp256k1::key::SecretKey;
67 use secp256k1::ecdh::SharedSecret;
69 /// Stores the info we will need to send when we want to forward an HTLC onwards
70 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
71 pub struct PendingForwardHTLCInfo {
72 pub(super) onion_packet: Option<msgs::OnionPacket>,
73 pub(super) incoming_shared_secret: SharedSecret,
74 pub(super) payment_hash: [u8; 32],
75 pub(super) short_channel_id: u64,
76 pub(super) amt_to_forward: u64,
77 pub(super) outgoing_cltv_value: u32,
80 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81 pub enum HTLCFailureMsg {
82 Relay(msgs::UpdateFailHTLC),
83 Malformed(msgs::UpdateFailMalformedHTLC),
86 /// Stores whether we can't forward an HTLC or relevant forwarding info
87 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88 pub enum PendingHTLCStatus {
89 Forward(PendingForwardHTLCInfo),
93 /// Tracks the inbound corresponding to an outbound HTLC
95 pub struct HTLCPreviousHopData {
96 pub(super) short_channel_id: u64,
97 pub(super) htlc_id: u64,
98 pub(super) incoming_packet_shared_secret: SharedSecret,
101 /// Tracks the inbound corresponding to an outbound HTLC
103 pub enum HTLCSource {
104 PreviousHopData(HTLCPreviousHopData),
107 session_priv: SecretKey,
108 /// Technically we can recalculate this from the route, but we cache it here to avoid
109 /// doing a double-pass on route when we get a failure back
110 first_hop_htlc_msat: u64,
115 pub fn dummy() -> Self {
116 HTLCSource::OutboundRoute {
117 route: Route { hops: Vec::new() },
118 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
119 first_hop_htlc_msat: 0,
124 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125 pub(crate) enum HTLCFailReason {
127 err: msgs::OnionErrorPacket,
135 pub(super) use self::channel_held_info::*;
137 struct MsgHandleErrInternal {
138 err: msgs::HandleError,
139 needs_channel_force_close: bool,
141 impl MsgHandleErrInternal {
143 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
147 action: Some(msgs::ErrorAction::SendErrorMessage {
148 msg: msgs::ErrorMessage {
150 data: err.to_string()
154 needs_channel_force_close: false,
158 fn send_err_msg_close_chan(err: &'static str, channel_id: [u8; 32]) -> Self {
162 action: Some(msgs::ErrorAction::SendErrorMessage {
163 msg: msgs::ErrorMessage {
165 data: err.to_string()
169 needs_channel_force_close: true,
173 fn from_maybe_close(err: msgs::HandleError) -> Self {
174 Self { err, needs_channel_force_close: true }
177 fn from_no_close(err: msgs::HandleError) -> Self {
178 Self { err, needs_channel_force_close: false }
181 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
184 ChannelError::Ignore(msg) => HandleError {
186 action: Some(msgs::ErrorAction::IgnoreError),
188 ChannelError::Close(msg) => HandleError {
190 action: Some(msgs::ErrorAction::SendErrorMessage {
191 msg: msgs::ErrorMessage {
193 data: msg.to_string()
198 needs_channel_force_close: false,
202 fn from_chan_maybe_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
205 ChannelError::Ignore(msg) => HandleError {
207 action: Some(msgs::ErrorAction::IgnoreError),
209 ChannelError::Close(msg) => HandleError {
211 action: Some(msgs::ErrorAction::SendErrorMessage {
212 msg: msgs::ErrorMessage {
214 data: msg.to_string()
219 needs_channel_force_close: true,
224 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
225 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
226 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
227 /// probably increase this significantly.
228 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
230 struct HTLCForwardInfo {
231 prev_short_channel_id: u64,
233 forward_info: PendingForwardHTLCInfo,
236 struct ChannelHolder {
237 by_id: HashMap<[u8; 32], Channel>,
238 short_to_id: HashMap<u64, [u8; 32]>,
239 next_forward: Instant,
240 /// short channel id -> forward infos. Key of 0 means payments received
241 /// Note that while this is held in the same mutex as the channels themselves, no consistency
242 /// guarantees are made about there existing a channel with the short id here, nor the short
243 /// ids in the PendingForwardHTLCInfo!
244 forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
245 /// Note that while this is held in the same mutex as the channels themselves, no consistency
246 /// guarantees are made about the channels given here actually existing anymore by the time you
248 claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
250 struct MutChannelHolder<'a> {
251 by_id: &'a mut HashMap<[u8; 32], Channel>,
252 short_to_id: &'a mut HashMap<u64, [u8; 32]>,
253 next_forward: &'a mut Instant,
254 forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
255 claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
258 fn borrow_parts(&mut self) -> MutChannelHolder {
260 by_id: &mut self.by_id,
261 short_to_id: &mut self.short_to_id,
262 next_forward: &mut self.next_forward,
263 forward_htlcs: &mut self.forward_htlcs,
264 claimable_htlcs: &mut self.claimable_htlcs,
269 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
270 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
272 /// Manager which keeps track of a number of channels and sends messages to the appropriate
273 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
275 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
276 /// to individual Channels.
277 pub struct ChannelManager {
278 genesis_hash: Sha256dHash,
279 fee_estimator: Arc<FeeEstimator>,
280 monitor: Arc<ManyChannelMonitor>,
281 chain_monitor: Arc<ChainWatchInterface>,
282 tx_broadcaster: Arc<BroadcasterInterface>,
284 announce_channels_publicly: bool,
285 fee_proportional_millionths: u32,
286 latest_block_height: AtomicUsize,
287 secp_ctx: Secp256k1<secp256k1::All>,
289 channel_state: Mutex<ChannelHolder>,
290 our_network_key: SecretKey,
292 pending_events: Mutex<Vec<events::Event>>,
297 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
298 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
299 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
300 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
301 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
302 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
303 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
305 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
306 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
307 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
308 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
311 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
313 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
314 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
317 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
319 macro_rules! secp_call {
320 ( $res: expr, $err: expr ) => {
323 Err(_) => return Err($err),
330 shared_secret: SharedSecret,
332 blinding_factor: [u8; 32],
333 ephemeral_pubkey: PublicKey,
338 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
339 pub struct ChannelDetails {
340 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
341 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
342 /// Note that this means this value is *not* persistent - it can change once during the
343 /// lifetime of the channel.
344 pub channel_id: [u8; 32],
345 /// The position of the funding transaction in the chain. None if the funding transaction has
346 /// not yet been confirmed and the channel fully opened.
347 pub short_channel_id: Option<u64>,
348 /// The node_id of our counterparty
349 pub remote_network_id: PublicKey,
350 /// The value, in satoshis, of this channel as appears in the funding output
351 pub channel_value_satoshis: u64,
352 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
356 impl ChannelManager {
357 /// Constructs a new ChannelManager to hold several channels and route between them.
359 /// This is the main "logic hub" for all channel-related actions, and implements
360 /// ChannelMessageHandler.
362 /// fee_proportional_millionths is an optional fee to charge any payments routed through us.
363 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
365 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
366 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> {
367 let secp_ctx = Secp256k1::new();
369 let res = Arc::new(ChannelManager {
370 genesis_hash: genesis_block(network).header.bitcoin_hash(),
371 fee_estimator: feeest.clone(),
372 monitor: monitor.clone(),
376 announce_channels_publicly,
377 fee_proportional_millionths,
378 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
381 channel_state: Mutex::new(ChannelHolder{
382 by_id: HashMap::new(),
383 short_to_id: HashMap::new(),
384 next_forward: Instant::now(),
385 forward_htlcs: HashMap::new(),
386 claimable_htlcs: HashMap::new(),
390 pending_events: Mutex::new(Vec::new()),
394 let weak_res = Arc::downgrade(&res);
395 res.chain_monitor.register_listener(weak_res);
399 /// Creates a new outbound channel to the given remote node and with the given value.
401 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
402 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
403 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
404 /// may wish to avoid using 0 for user_id here.
406 /// If successful, will generate a SendOpenChannel event, so you should probably poll
407 /// PeerManager::process_events afterwards.
409 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat being greater than channel_value_satoshis * 1k
410 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
411 let chan_keys = if cfg!(feature = "fuzztarget") {
413 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(),
414 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(),
415 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(),
416 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(),
417 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(),
418 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(),
419 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(),
420 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],
423 let mut key_seed = [0u8; 32];
424 rng::fill_bytes(&mut key_seed);
425 match ChannelKeys::new_from_seed(&key_seed) {
427 Err(_) => panic!("RNG is busted!")
431 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))?;
432 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
433 let mut channel_state = self.channel_state.lock().unwrap();
434 match channel_state.by_id.entry(channel.channel_id()) {
435 hash_map::Entry::Occupied(_) => {
436 if cfg!(feature = "fuzztarget") {
437 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
439 panic!("RNG is bad???");
442 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
445 let mut events = self.pending_events.lock().unwrap();
446 events.push(events::Event::SendOpenChannel {
447 node_id: their_network_key,
453 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
454 /// more information.
455 pub fn list_channels(&self) -> Vec<ChannelDetails> {
456 let channel_state = self.channel_state.lock().unwrap();
457 let mut res = Vec::with_capacity(channel_state.by_id.len());
458 for (channel_id, channel) in channel_state.by_id.iter() {
459 res.push(ChannelDetails {
460 channel_id: (*channel_id).clone(),
461 short_channel_id: channel.get_short_channel_id(),
462 remote_network_id: channel.get_their_node_id(),
463 channel_value_satoshis: channel.get_value_satoshis(),
464 user_id: channel.get_user_id(),
470 /// Gets the list of usable channels, in random order. Useful as an argument to
471 /// Router::get_route to ensure non-announced channels are used.
472 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
473 let channel_state = self.channel_state.lock().unwrap();
474 let mut res = Vec::with_capacity(channel_state.by_id.len());
475 for (channel_id, channel) in channel_state.by_id.iter() {
476 // Note we use is_live here instead of usable which leads to somewhat confused
477 // internal/external nomenclature, but that's ok cause that's probably what the user
478 // really wanted anyway.
479 if channel.is_live() {
480 res.push(ChannelDetails {
481 channel_id: (*channel_id).clone(),
482 short_channel_id: channel.get_short_channel_id(),
483 remote_network_id: channel.get_their_node_id(),
484 channel_value_satoshis: channel.get_value_satoshis(),
485 user_id: channel.get_user_id(),
492 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
493 /// will be accepted on the given channel, and after additional timeout/the closing of all
494 /// pending HTLCs, the channel will be closed on chain.
496 /// May generate a SendShutdown event on success, which should be relayed.
497 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
498 let (mut res, node_id, chan_option) = {
499 let mut channel_state_lock = self.channel_state.lock().unwrap();
500 let channel_state = channel_state_lock.borrow_parts();
501 match channel_state.by_id.entry(channel_id.clone()) {
502 hash_map::Entry::Occupied(mut chan_entry) => {
503 let res = chan_entry.get_mut().get_shutdown()?;
504 if chan_entry.get().is_shutdown() {
505 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
506 channel_state.short_to_id.remove(&short_id);
508 (res, chan_entry.get().get_their_node_id(), Some(chan_entry.remove_entry().1))
509 } else { (res, chan_entry.get().get_their_node_id(), None) }
511 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
514 for htlc_source in res.1.drain(..) {
515 // unknown_next_peer...I dunno who that is anymore....
516 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
518 let chan_update = if let Some(chan) = chan_option {
519 if let Ok(update) = self.get_channel_update(&chan) {
524 let mut events = self.pending_events.lock().unwrap();
525 if let Some(update) = chan_update {
526 events.push(events::Event::BroadcastChannelUpdate {
530 events.push(events::Event::SendShutdown {
539 fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>)) {
540 let (local_txn, mut failed_htlcs) = shutdown_res;
541 for htlc_source in failed_htlcs.drain(..) {
542 // unknown_next_peer...I dunno who that is anymore....
543 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
545 for tx in local_txn {
546 self.tx_broadcaster.broadcast_transaction(&tx);
548 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
549 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
550 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
551 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
552 //timeouts are hit and our claims confirm).
553 //TODO: In any case, we need to make sure we remove any pending htlc tracking (via
554 //fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
557 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
558 /// the chain and rejecting new HTLCs on the given channel.
559 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
561 let mut channel_state_lock = self.channel_state.lock().unwrap();
562 let channel_state = channel_state_lock.borrow_parts();
563 if let Some(chan) = channel_state.by_id.remove(channel_id) {
564 if let Some(short_id) = chan.get_short_channel_id() {
565 channel_state.short_to_id.remove(&short_id);
572 self.finish_force_close_channel(chan.force_shutdown());
573 let mut events = self.pending_events.lock().unwrap();
574 if let Ok(update) = self.get_channel_update(&chan) {
575 events.push(events::Event::BroadcastChannelUpdate {
581 /// Force close all channels, immediately broadcasting the latest local commitment transaction
582 /// for each to the chain and rejecting new HTLCs on each.
583 pub fn force_close_all_channels(&self) {
584 for chan in self.list_channels() {
585 self.force_close_channel(&chan.channel_id);
590 fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
592 let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
593 hmac.input(&shared_secret[..]);
594 let mut res = [0; 32];
595 hmac.raw_result(&mut res);
599 let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
600 hmac.input(&shared_secret[..]);
601 let mut res = [0; 32];
602 hmac.raw_result(&mut res);
608 fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
609 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
610 hmac.input(&shared_secret[..]);
611 let mut res = [0; 32];
612 hmac.raw_result(&mut res);
617 fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
618 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
619 hmac.input(&shared_secret[..]);
620 let mut res = [0; 32];
621 hmac.raw_result(&mut res);
625 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
627 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<(), secp256k1::Error> {
628 let mut blinded_priv = session_priv.clone();
629 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
631 for hop in route.hops.iter() {
632 let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
634 let mut sha = Sha256::new();
635 sha.input(&blinded_pub.serialize()[..]);
636 sha.input(&shared_secret[..]);
637 let mut blinding_factor = [0u8; 32];
638 sha.result(&mut blinding_factor);
640 let ephemeral_pubkey = blinded_pub;
642 blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
643 blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
645 callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
651 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
652 fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
653 let mut res = Vec::with_capacity(route.hops.len());
655 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
656 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
662 blinding_factor: _blinding_factor,
672 /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
673 fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
674 let mut cur_value_msat = 0u64;
675 let mut cur_cltv = starting_htlc_offset;
676 let mut last_short_channel_id = 0;
677 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
678 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
679 unsafe { res.set_len(route.hops.len()); }
681 for (idx, hop) in route.hops.iter().enumerate().rev() {
682 // First hop gets special values so that it can check, on receipt, that everything is
683 // exactly as it should be (and the next hop isn't trying to probe to find out if we're
684 // the intended recipient).
685 let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
686 let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
687 res[idx] = msgs::OnionHopData {
689 data: msgs::OnionRealm0HopData {
690 short_channel_id: last_short_channel_id,
691 amt_to_forward: value_msat,
692 outgoing_cltv_value: cltv,
696 cur_value_msat += hop.fee_msat;
697 if cur_value_msat >= 21000000 * 100000000 * 1000 {
698 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
700 cur_cltv += hop.cltv_expiry_delta as u32;
701 if cur_cltv >= 500000000 {
702 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
704 last_short_channel_id = hop.short_channel_id;
706 Ok((res, cur_value_msat, cur_cltv))
710 fn shift_arr_right(arr: &mut [u8; 20*65]) {
712 ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
720 fn xor_bufs(dst: &mut[u8], src: &[u8]) {
721 assert_eq!(dst.len(), src.len());
723 for i in 0..dst.len() {
728 const ZERO:[u8; 21*65] = [0; 21*65];
729 fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
730 let mut buf = Vec::with_capacity(21*65);
731 buf.resize(21*65, 0);
734 let iters = payloads.len() - 1;
735 let end_len = iters * 65;
736 let mut res = Vec::with_capacity(end_len);
737 res.resize(end_len, 0);
739 for (i, keys) in onion_keys.iter().enumerate() {
740 if i == payloads.len() - 1 { continue; }
741 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
742 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
743 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
748 let mut packet_data = [0; 20*65];
749 let mut hmac_res = [0; 32];
751 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
752 ChannelManager::shift_arr_right(&mut packet_data);
753 payload.hmac = hmac_res;
754 packet_data[0..65].copy_from_slice(&payload.encode()[..]);
756 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
757 chacha.process(&packet_data, &mut buf[0..20*65]);
758 packet_data[..].copy_from_slice(&buf[0..20*65]);
761 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
764 let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
765 hmac.input(&packet_data);
766 hmac.input(&associated_data[..]);
767 hmac.raw_result(&mut hmac_res);
772 public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
773 hop_data: packet_data,
778 /// Encrypts a failure packet. raw_packet can either be a
779 /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
780 fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
781 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
783 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
784 packet_crypted.resize(raw_packet.len(), 0);
785 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
786 chacha.process(&raw_packet, &mut packet_crypted[..]);
787 msgs::OnionErrorPacket {
788 data: packet_crypted,
792 fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
793 assert!(failure_data.len() <= 256 - 2);
795 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
798 let mut res = Vec::with_capacity(2 + failure_data.len());
799 res.push(((failure_type >> 8) & 0xff) as u8);
800 res.push(((failure_type >> 0) & 0xff) as u8);
801 res.extend_from_slice(&failure_data[..]);
805 let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
806 res.resize(256 - 2 - failure_data.len(), 0);
809 let mut packet = msgs::DecodedOnionErrorPacket {
811 failuremsg: failuremsg,
815 let mut hmac = Hmac::new(Sha256::new(), &um);
816 hmac.input(&packet.encode()[32..]);
817 hmac.raw_result(&mut packet.hmac);
823 fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
824 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
825 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
828 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
829 macro_rules! get_onion_hash {
832 let mut sha = Sha256::new();
833 sha.input(&msg.onion_routing_packet.hop_data);
834 let mut onion_hash = [0; 32];
835 sha.result(&mut onion_hash);
841 if let Err(_) = msg.onion_routing_packet.public_key {
842 log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
843 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
844 channel_id: msg.channel_id,
845 htlc_id: msg.htlc_id,
846 sha256_of_onion: get_onion_hash!(),
847 failure_code: 0x8000 | 0x4000 | 6,
848 })), self.channel_state.lock().unwrap());
851 let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key);
852 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
854 let mut channel_state = None;
855 macro_rules! return_err {
856 ($msg: expr, $err_code: expr, $data: expr) => {
858 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
859 if channel_state.is_none() {
860 channel_state = Some(self.channel_state.lock().unwrap());
862 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
863 channel_id: msg.channel_id,
864 htlc_id: msg.htlc_id,
865 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
866 })), channel_state.unwrap());
871 if msg.onion_routing_packet.version != 0 {
872 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
873 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
874 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
875 //receiving node would have to brute force to figure out which version was put in the
876 //packet by the node that send us the message, in the case of hashing the hop_data, the
877 //node knows the HMAC matched, so they already know what is there...
878 return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
881 let mut hmac = Hmac::new(Sha256::new(), &mu);
882 hmac.input(&msg.onion_routing_packet.hop_data);
883 hmac.input(&msg.payment_hash);
884 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
885 return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
888 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
889 let next_hop_data = {
890 let mut decoded = [0; 65];
891 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
892 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
894 let error_code = match err {
895 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
896 _ => 0x2000 | 2, // Should never happen
898 return_err!("Unable to decode our hop data", error_code, &[0;0]);
904 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
906 // final_expiry_too_soon
907 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
908 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
910 // final_incorrect_htlc_amount
911 if next_hop_data.data.amt_to_forward > msg.amount_msat {
912 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
914 // final_incorrect_cltv_expiry
915 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
916 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
919 // Note that we could obviously respond immediately with an update_fulfill_htlc
920 // message, however that would leak that we are the recipient of this payment, so
921 // instead we stay symmetric with the forwarding case, only responding (after a
922 // delay) once they've send us a commitment_signed!
924 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
926 payment_hash: msg.payment_hash.clone(),
928 incoming_shared_secret: shared_secret.clone(),
929 amt_to_forward: next_hop_data.data.amt_to_forward,
930 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
933 let mut new_packet_data = [0; 20*65];
934 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
935 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
937 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
939 let blinding_factor = {
940 let mut sha = Sha256::new();
941 sha.input(&new_pubkey.serialize()[..]);
942 sha.input(&shared_secret[..]);
943 let mut res = [0u8; 32];
944 sha.result(&mut res);
945 match SecretKey::from_slice(&self.secp_ctx, &res) {
947 return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
953 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
954 return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
957 let outgoing_packet = msgs::OnionPacket {
959 public_key: Ok(new_pubkey),
960 hop_data: new_packet_data,
961 hmac: next_hop_data.hmac.clone(),
964 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
965 onion_packet: Some(outgoing_packet),
966 payment_hash: msg.payment_hash.clone(),
967 short_channel_id: next_hop_data.data.short_channel_id,
968 incoming_shared_secret: shared_secret.clone(),
969 amt_to_forward: next_hop_data.data.amt_to_forward,
970 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
974 channel_state = Some(self.channel_state.lock().unwrap());
975 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
976 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
977 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
978 let forwarding_id = match id_option {
979 None => { // unknown_next_peer
980 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
982 Some(id) => id.clone(),
984 if let Some((err, code, chan_update)) = loop {
985 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
987 if !chan.is_live() { // channel_disabled
988 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
990 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
991 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
993 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) });
994 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
995 break Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, Some(self.get_channel_update(chan).unwrap())));
997 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
998 break Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, Some(self.get_channel_update(chan).unwrap())));
1000 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1001 // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1002 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1003 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1005 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1006 break Some(("CLTV expiry is too far in the future", 21, None));
1011 let mut res = Vec::with_capacity(8 + 128);
1012 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1013 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1015 else if code == 0x1000 | 13 {
1016 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1018 if let Some(chan_update) = chan_update {
1019 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1021 return_err!(err, code, &res[..]);
1026 (pending_forward_info, channel_state.unwrap())
1029 /// only fails if the channel does not yet have an assigned short_id
1030 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1031 let short_channel_id = match chan.get_short_channel_id() {
1032 None => return Err(HandleError{err: "Channel not yet established", action: None}),
1036 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1038 let unsigned = msgs::UnsignedChannelUpdate {
1039 chain_hash: self.genesis_hash,
1040 short_channel_id: short_channel_id,
1041 timestamp: chan.get_channel_update_count(),
1042 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1043 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1044 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1045 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1046 fee_proportional_millionths: self.fee_proportional_millionths,
1047 excess_data: Vec::new(),
1050 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1051 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1053 Ok(msgs::ChannelUpdate {
1059 /// Sends a payment along a given route.
1061 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1062 /// fields for more info.
1064 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1065 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1066 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1067 /// specified in the last hop in the route! Thus, you should probably do your own
1068 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1069 /// payment") and prevent double-sends yourself.
1071 /// May generate a SendHTLCs event on success, which should be relayed.
1073 /// Raises APIError::RoutError when invalid route or forward parameter
1074 /// (cltv_delta, fee, node public key) is specified
1075 pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1076 if route.hops.len() < 1 || route.hops.len() > 20 {
1077 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1079 let our_node_id = self.get_our_node_id();
1080 for (idx, hop) in route.hops.iter().enumerate() {
1081 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1082 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1086 let session_priv = SecretKey::from_slice(&self.secp_ctx, &{
1087 let mut session_key = [0; 32];
1088 rng::fill_bytes(&mut session_key);
1090 }).expect("RNG is bad!");
1092 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1094 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1095 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1096 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1097 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1099 let (first_hop_node_id, (update_add, commitment_signed, chan_monitor)) = {
1100 let mut channel_state_lock = self.channel_state.lock().unwrap();
1101 let channel_state = channel_state_lock.borrow_parts();
1103 let id = match channel_state.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1104 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1105 Some(id) => id.clone(),
1109 let chan = channel_state.by_id.get_mut(&id).unwrap();
1110 if chan.get_their_node_id() != route.hops.first().unwrap().pubkey {
1111 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1113 if !chan.is_live() {
1114 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected!"});
1116 chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1117 route: route.clone(),
1118 session_priv: session_priv.clone(),
1119 first_hop_htlc_msat: htlc_msat,
1120 }, onion_packet).map_err(|he| APIError::ChannelUnavailable{err: he.err})?
1123 let first_hop_node_id = route.hops.first().unwrap().pubkey;
1126 Some(msgs) => (first_hop_node_id, msgs),
1127 None => return Ok(()),
1131 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1135 let mut events = self.pending_events.lock().unwrap();
1136 events.push(events::Event::UpdateHTLCs {
1137 node_id: first_hop_node_id,
1138 updates: msgs::CommitmentUpdate {
1139 update_add_htlcs: vec![update_add],
1140 update_fulfill_htlcs: Vec::new(),
1141 update_fail_htlcs: Vec::new(),
1142 update_fail_malformed_htlcs: Vec::new(),
1150 /// Call this upon creation of a funding transaction for the given channel.
1152 /// Panics if a funding transaction has already been provided for this channel.
1154 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1155 /// be trivially prevented by using unique funding transaction keys per-channel).
1156 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1157 macro_rules! add_pending_event {
1160 let mut pending_events = self.pending_events.lock().unwrap();
1161 pending_events.push($event);
1166 let (chan, msg, chan_monitor) = {
1167 let mut channel_state = self.channel_state.lock().unwrap();
1168 match channel_state.by_id.remove(temporary_channel_id) {
1170 match chan.get_outbound_funding_created(funding_txo) {
1171 Ok(funding_msg) => {
1172 (chan, funding_msg.0, funding_msg.1)
1175 log_error!(self, "Got bad signatures: {}!", e.err);
1176 mem::drop(channel_state);
1177 add_pending_event!(events::Event::HandleError {
1178 node_id: chan.get_their_node_id(),
1187 }; // Release channel lock for install_watch_outpoint call,
1188 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1191 add_pending_event!(events::Event::SendFundingCreated {
1192 node_id: chan.get_their_node_id(),
1196 let mut channel_state = self.channel_state.lock().unwrap();
1197 match channel_state.by_id.entry(chan.channel_id()) {
1198 hash_map::Entry::Occupied(_) => {
1199 panic!("Generated duplicate funding txid?");
1201 hash_map::Entry::Vacant(e) => {
1207 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1208 if !chan.should_announce() { return None }
1210 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1212 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1214 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1215 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1217 Some(msgs::AnnouncementSignatures {
1218 channel_id: chan.channel_id(),
1219 short_channel_id: chan.get_short_channel_id().unwrap(),
1220 node_signature: our_node_sig,
1221 bitcoin_signature: our_bitcoin_sig,
1225 /// Processes HTLCs which are pending waiting on random forward delay.
1227 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1228 /// Will likely generate further events.
1229 pub fn process_pending_htlc_forwards(&self) {
1230 let mut new_events = Vec::new();
1231 let mut failed_forwards = Vec::new();
1233 let mut channel_state_lock = self.channel_state.lock().unwrap();
1234 let channel_state = channel_state_lock.borrow_parts();
1236 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1240 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1241 if short_chan_id != 0 {
1242 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1243 Some(chan_id) => chan_id.clone(),
1245 failed_forwards.reserve(pending_forwards.len());
1246 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1247 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1248 short_channel_id: prev_short_channel_id,
1249 htlc_id: prev_htlc_id,
1250 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1252 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1257 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1259 let mut add_htlc_msgs = Vec::new();
1260 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1261 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1262 short_channel_id: prev_short_channel_id,
1263 htlc_id: prev_htlc_id,
1264 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1266 match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
1268 let chan_update = self.get_channel_update(forward_chan).unwrap();
1269 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1274 Some(msg) => { add_htlc_msgs.push(msg); },
1276 // Nothing to do here...we're waiting on a remote
1277 // revoke_and_ack before we can add anymore HTLCs. The Channel
1278 // will automatically handle building the update_add_htlc and
1279 // commitment_signed messages when we can.
1280 // TODO: Do some kind of timer to set the channel as !is_live()
1281 // as we don't really want others relying on us relaying through
1282 // this channel currently :/.
1289 if !add_htlc_msgs.is_empty() {
1290 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1293 if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(ref _err_msg)}) = &e.action {
1294 } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: ref _err_msg}) = &e.action {
1296 panic!("Stated return value requirements in send_commitment() were not met");
1298 //TODO: Handle...this is bad!
1302 new_events.push((Some(monitor), events::Event::UpdateHTLCs {
1303 node_id: forward_chan.get_their_node_id(),
1304 updates: msgs::CommitmentUpdate {
1305 update_add_htlcs: add_htlc_msgs,
1306 update_fulfill_htlcs: Vec::new(),
1307 update_fail_htlcs: Vec::new(),
1308 update_fail_malformed_htlcs: Vec::new(),
1310 commitment_signed: commitment_msg,
1315 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1316 let prev_hop_data = HTLCPreviousHopData {
1317 short_channel_id: prev_short_channel_id,
1318 htlc_id: prev_htlc_id,
1319 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1321 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1322 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1323 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1325 new_events.push((None, events::Event::PaymentReceived {
1326 payment_hash: forward_info.payment_hash,
1327 amt: forward_info.amt_to_forward,
1334 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1336 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1337 Some(chan_update) => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: chan_update.encode_with_len() }),
1341 if new_events.is_empty() { return }
1343 new_events.retain(|event| {
1344 if let &Some(ref monitor) = &event.0 {
1345 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor.clone()) {
1346 unimplemented!();// but def dont push the event...
1352 let mut events = self.pending_events.lock().unwrap();
1353 events.reserve(new_events.len());
1354 for event in new_events.drain(..) {
1355 events.push(event.1);
1359 /// Indicates that the preimage for payment_hash is unknown after a PaymentReceived event.
1360 pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32]) -> bool {
1361 // TODO: Add ability to return 0x4000|16 (incorrect_payment_amount) if the amount we
1362 // received is < expected or > 2*expected
1363 let mut channel_state = Some(self.channel_state.lock().unwrap());
1364 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1365 if let Some(mut sources) = removed_source {
1366 for htlc_with_hash in sources.drain(..) {
1367 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1368 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: Vec::new() });
1374 /// Fails an HTLC backwards to the sender of it to us.
1375 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1376 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1377 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1378 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1379 /// still-available channels.
1380 fn fail_htlc_backwards_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1382 HTLCSource::OutboundRoute { .. } => {
1383 mem::drop(channel_state);
1385 let mut pending_events = self.pending_events.lock().unwrap();
1386 pending_events.push(events::Event::PaymentFailed {
1387 payment_hash: payment_hash.clone()
1390 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1391 let err_packet = match onion_error {
1392 HTLCFailReason::Reason { failure_code, data } => {
1393 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1394 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1396 HTLCFailReason::ErrorPacket { err } => {
1397 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1401 let (node_id, fail_msgs) = {
1402 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1403 Some(chan_id) => chan_id.clone(),
1407 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1408 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1409 Ok(msg) => (chan.get_their_node_id(), msg),
1411 //TODO: Do something with e?
1418 Some((msg, commitment_msg, chan_monitor)) => {
1419 mem::drop(channel_state);
1421 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1422 unimplemented!();// but def dont push the event...
1425 let mut pending_events = self.pending_events.lock().unwrap();
1426 pending_events.push(events::Event::UpdateHTLCs {
1428 updates: msgs::CommitmentUpdate {
1429 update_add_htlcs: Vec::new(),
1430 update_fulfill_htlcs: Vec::new(),
1431 update_fail_htlcs: vec![msg],
1432 update_fail_malformed_htlcs: Vec::new(),
1434 commitment_signed: commitment_msg,
1444 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1445 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1446 /// should probably kick the net layer to go send messages if this returns true!
1448 /// May panic if called except in response to a PaymentReceived event.
1449 pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1450 let mut sha = Sha256::new();
1451 sha.input(&payment_preimage);
1452 let mut payment_hash = [0; 32];
1453 sha.result(&mut payment_hash);
1455 let mut channel_state = Some(self.channel_state.lock().unwrap());
1456 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1457 if let Some(mut sources) = removed_source {
1458 for htlc_with_hash in sources.drain(..) {
1459 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1460 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1465 fn claim_funds_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1467 HTLCSource::OutboundRoute { .. } => {
1468 mem::drop(channel_state);
1469 let mut pending_events = self.pending_events.lock().unwrap();
1470 pending_events.push(events::Event::PaymentSent {
1474 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1475 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1476 let (node_id, fulfill_msgs) = {
1477 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1478 Some(chan_id) => chan_id.clone(),
1480 // TODO: There is probably a channel manager somewhere that needs to
1481 // learn the preimage as the channel already hit the chain and that's
1487 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1488 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1489 Ok(msg) => (chan.get_their_node_id(), msg),
1491 // TODO: There is probably a channel manager somewhere that needs to
1492 // learn the preimage as the channel may be about to hit the chain.
1493 //TODO: Do something with e?
1499 mem::drop(channel_state);
1500 if let Some(chan_monitor) = fulfill_msgs.1 {
1501 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1502 unimplemented!();// but def dont push the event...
1506 if let Some((msg, commitment_msg)) = fulfill_msgs.0 {
1507 let mut pending_events = self.pending_events.lock().unwrap();
1508 pending_events.push(events::Event::UpdateHTLCs {
1510 updates: msgs::CommitmentUpdate {
1511 update_add_htlcs: Vec::new(),
1512 update_fulfill_htlcs: vec![msg],
1513 update_fail_htlcs: Vec::new(),
1514 update_fail_malformed_htlcs: Vec::new(),
1516 commitment_signed: commitment_msg,
1524 /// Gets the node_id held by this ChannelManager
1525 pub fn get_our_node_id(&self) -> PublicKey {
1526 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1529 /// Used to restore channels to normal operation after a
1530 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1532 pub fn test_restore_channel_monitor(&self) {
1536 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, MsgHandleErrInternal> {
1537 if msg.chain_hash != self.genesis_hash {
1538 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1540 let mut channel_state = self.channel_state.lock().unwrap();
1541 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
1542 return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone()));
1545 let chan_keys = if cfg!(feature = "fuzztarget") {
1547 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(),
1548 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(),
1549 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(),
1550 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(),
1551 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(),
1552 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(),
1553 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(),
1554 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],
1557 let mut key_seed = [0u8; 32];
1558 rng::fill_bytes(&mut key_seed);
1559 match ChannelKeys::new_from_seed(&key_seed) {
1561 Err(_) => panic!("RNG is busted!")
1565 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))
1566 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1567 let accept_msg = channel.get_accept_channel();
1568 channel_state.by_id.insert(channel.channel_id(), channel);
1572 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1573 let (value, output_script, user_id) = {
1574 let mut channel_state = self.channel_state.lock().unwrap();
1575 match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
1577 if chan.get_their_node_id() != *their_node_id {
1578 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1579 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1581 chan.accept_channel(&msg)
1582 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.temporary_channel_id))?;
1583 (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
1585 //TODO: same as above
1586 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1589 let mut pending_events = self.pending_events.lock().unwrap();
1590 pending_events.push(events::Event::FundingGenerationReady {
1591 temporary_channel_id: msg.temporary_channel_id,
1592 channel_value_satoshis: value,
1593 output_script: output_script,
1594 user_channel_id: user_id,
1599 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, MsgHandleErrInternal> {
1600 let (chan, funding_msg, monitor_update) = {
1601 let mut channel_state = self.channel_state.lock().unwrap();
1602 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1603 hash_map::Entry::Occupied(mut chan) => {
1604 if chan.get().get_their_node_id() != *their_node_id {
1605 //TODO: here and below MsgHandleErrInternal, #153 case
1606 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1608 match chan.get_mut().funding_created(msg) {
1609 Ok((funding_msg, monitor_update)) => {
1610 (chan.remove(), funding_msg, monitor_update)
1613 return Err(e).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1617 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1619 }; // Release channel lock for install_watch_outpoint call,
1620 // note that this means if the remote end is misbehaving and sends a message for the same
1621 // channel back-to-back with funding_created, we'll end up thinking they sent a message
1622 // for a bogus channel.
1623 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1626 let mut channel_state = self.channel_state.lock().unwrap();
1627 match channel_state.by_id.entry(funding_msg.channel_id) {
1628 hash_map::Entry::Occupied(_) => {
1629 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1631 hash_map::Entry::Vacant(e) => {
1638 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1639 let (funding_txo, user_id, monitor) = {
1640 let mut channel_state = self.channel_state.lock().unwrap();
1641 match channel_state.by_id.get_mut(&msg.channel_id) {
1643 if chan.get_their_node_id() != *their_node_id {
1644 //TODO: here and below MsgHandleErrInternal, #153 case
1645 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1647 let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1648 (chan.get_funding_txo().unwrap(), chan.get_user_id(), chan_monitor)
1650 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1653 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1656 let mut pending_events = self.pending_events.lock().unwrap();
1657 pending_events.push(events::Event::FundingBroadcastSafe {
1658 funding_txo: funding_txo,
1659 user_channel_id: user_id,
1664 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, MsgHandleErrInternal> {
1665 let mut channel_state = self.channel_state.lock().unwrap();
1666 match channel_state.by_id.get_mut(&msg.channel_id) {
1668 if chan.get_their_node_id() != *their_node_id {
1669 //TODO: here and below MsgHandleErrInternal, #153 case
1670 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1672 chan.funding_locked(&msg)
1673 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
1674 return Ok(self.get_announcement_sigs(chan));
1676 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1680 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), MsgHandleErrInternal> {
1681 let (mut res, chan_option) = {
1682 let mut channel_state_lock = self.channel_state.lock().unwrap();
1683 let channel_state = channel_state_lock.borrow_parts();
1685 match channel_state.by_id.entry(msg.channel_id.clone()) {
1686 hash_map::Entry::Occupied(mut chan_entry) => {
1687 if chan_entry.get().get_their_node_id() != *their_node_id {
1688 //TODO: here and below MsgHandleErrInternal, #153 case
1689 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1691 let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1692 if chan_entry.get().is_shutdown() {
1693 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1694 channel_state.short_to_id.remove(&short_id);
1696 (res, Some(chan_entry.remove_entry().1))
1697 } else { (res, None) }
1699 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1702 for htlc_source in res.2.drain(..) {
1703 // unknown_next_peer...I dunno who that is anymore....
1704 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1706 if let Some(chan) = chan_option {
1707 if let Ok(update) = self.get_channel_update(&chan) {
1708 let mut events = self.pending_events.lock().unwrap();
1709 events.push(events::Event::BroadcastChannelUpdate {
1717 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, MsgHandleErrInternal> {
1718 let (res, chan_option) = {
1719 let mut channel_state_lock = self.channel_state.lock().unwrap();
1720 let channel_state = channel_state_lock.borrow_parts();
1721 match channel_state.by_id.entry(msg.channel_id.clone()) {
1722 hash_map::Entry::Occupied(mut chan_entry) => {
1723 if chan_entry.get().get_their_node_id() != *their_node_id {
1724 //TODO: here and below MsgHandleErrInternal, #153 case
1725 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1727 let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1728 if res.1.is_some() {
1729 // We're done with this channel, we've got a signed closing transaction and
1730 // will send the closing_signed back to the remote peer upon return. This
1731 // also implies there are no pending HTLCs left on the channel, so we can
1732 // fully delete it from tracking (the channel monitor is still around to
1733 // watch for old state broadcasts)!
1734 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1735 channel_state.short_to_id.remove(&short_id);
1737 (res, Some(chan_entry.remove_entry().1))
1738 } else { (res, None) }
1740 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1743 if let Some(broadcast_tx) = res.1 {
1744 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1746 if let Some(chan) = chan_option {
1747 if let Ok(update) = self.get_channel_update(&chan) {
1748 let mut events = self.pending_events.lock().unwrap();
1749 events.push(events::Event::BroadcastChannelUpdate {
1757 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1758 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1759 //determine the state of the payment based on our response/if we forward anything/the time
1760 //we take to respond. We should take care to avoid allowing such an attack.
1762 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1763 //us repeatedly garbled in different ways, and compare our error messages, which are
1764 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1765 //but we should prevent it anyway.
1767 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1768 let channel_state = channel_state_lock.borrow_parts();
1770 match channel_state.by_id.get_mut(&msg.channel_id) {
1772 if chan.get_their_node_id() != *their_node_id {
1773 //TODO: here MsgHandleErrInternal, #153 case
1774 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1776 if !chan.is_usable() {
1777 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Channel not yet available for receiving HTLCs", action: Some(msgs::ErrorAction::IgnoreError)}));
1779 chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1781 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1785 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1786 let mut channel_state = self.channel_state.lock().unwrap();
1787 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
1789 if chan.get_their_node_id() != *their_node_id {
1790 //TODO: here and below MsgHandleErrInternal, #153 case
1791 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1793 chan.update_fulfill_htlc(&msg)
1794 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?.clone()
1796 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1798 self.claim_funds_internal(channel_state, htlc_source, msg.payment_preimage.clone());
1802 // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
1803 // indicating that the payment itself failed
1804 fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
1805 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
1806 macro_rules! onion_failure_log {
1807 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
1808 log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
1810 ( $error_code_textual: expr, $error_code: expr ) => {
1811 log_trace!(self, "{}({})", $error_code_textual, $error_code);
1815 const BADONION: u16 = 0x8000;
1816 const PERM: u16 = 0x4000;
1817 const UPDATE: u16 = 0x1000;
1820 let mut htlc_msat = *first_hop_htlc_msat;
1822 // Handle packed channel/node updates for passing back for the route handler
1823 Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
1824 if res.is_some() { return; }
1826 let incoming_htlc_msat = htlc_msat;
1827 let amt_to_forward = htlc_msat - route_hop.fee_msat;
1828 htlc_msat = amt_to_forward;
1830 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
1832 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1833 decryption_tmp.resize(packet_decrypted.len(), 0);
1834 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1835 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1836 packet_decrypted = decryption_tmp;
1838 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
1840 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
1841 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
1842 let mut hmac = Hmac::new(Sha256::new(), &um);
1843 hmac.input(&err_packet.encode()[32..]);
1844 let mut calc_tag = [0u8; 32];
1845 hmac.raw_result(&mut calc_tag);
1847 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
1848 if err_packet.failuremsg.len() < 2 {
1849 // Useless packet that we can't use but it passed HMAC, so it
1850 // definitely came from the peer in question
1851 res = Some((None, !is_from_final_node));
1853 let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
1855 match error_code & 0xff {
1857 // either from an intermediate or final node
1858 // invalid_realm(PERM|1),
1859 // temporary_node_failure(NODE|2)
1860 // permanent_node_failure(PERM|NODE|2)
1861 // required_node_feature_mssing(PERM|NODE|3)
1862 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1863 node_id: route_hop.pubkey,
1864 is_permanent: error_code & PERM == PERM,
1865 }), !(error_code & PERM == PERM && is_from_final_node)));
1866 // node returning invalid_realm is removed from network_map,
1867 // although NODE flag is not set, TODO: or remove channel only?
1868 // retry payment when removed node is not a final node
1874 if is_from_final_node {
1875 let payment_retryable = match error_code {
1876 c if c == PERM|15 => false, // unknown_payment_hash
1877 c if c == PERM|16 => false, // incorrect_payment_amount
1878 17 => true, // final_expiry_too_soon
1879 18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
1880 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
1883 19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
1884 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1888 // A final node has sent us either an invalid code or an error_code that
1889 // MUST be sent from the processing node, or the formmat of failuremsg
1890 // does not coform to the spec.
1891 // Remove it from the network map and don't may retry payment
1892 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1893 node_id: route_hop.pubkey,
1899 res = Some((None, payment_retryable));
1903 // now, error_code should be only from the intermediate nodes
1905 _c if error_code & PERM == PERM => {
1906 res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1907 short_channel_id: route_hop.short_channel_id,
1911 _c if error_code & UPDATE == UPDATE => {
1912 let offset = match error_code {
1913 c if c == UPDATE|7 => 0, // temporary_channel_failure
1914 c if c == UPDATE|11 => 8, // amount_below_minimum
1915 c if c == UPDATE|12 => 8, // fee_insufficient
1916 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
1917 c if c == UPDATE|14 => 0, // expiry_too_soon
1918 c if c == UPDATE|20 => 2, // channel_disabled
1920 // node sending unknown code
1921 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1922 node_id: route_hop.pubkey,
1929 if err_packet.failuremsg.len() >= offset + 2 {
1930 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
1931 if err_packet.failuremsg.len() >= offset + 4 + update_len {
1932 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
1933 // if channel_update should NOT have caused the failure:
1934 // MAY treat the channel_update as invalid.
1935 let is_chan_update_invalid = match error_code {
1936 c if c == UPDATE|7 => { // temporary_channel_failure
1939 c if c == UPDATE|11 => { // amount_below_minimum
1940 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1941 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
1942 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
1944 c if c == UPDATE|12 => { // fee_insufficient
1945 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1946 let new_fee = amt_to_forward.checked_mul(chan_update.contents.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan_update.contents.fee_base_msat as u64) });
1947 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
1948 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
1950 c if c == UPDATE|13 => { // incorrect_cltv_expiry
1951 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
1952 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
1953 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
1955 c if c == UPDATE|20 => { // channel_disabled
1956 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
1957 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
1958 chan_update.contents.flags & 0x01 == 0x01
1960 c if c == UPDATE|21 => true, // expiry_too_far
1961 _ => { unreachable!(); },
1964 let msg = if is_chan_update_invalid { None } else {
1965 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1969 res = Some((msg, true));
1975 _c if error_code & BADONION == BADONION => {
1978 14 => { // expiry_too_soon
1979 res = Some((None, true));
1983 // node sending unknown code
1984 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1985 node_id: route_hop.pubkey,
1994 }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
1995 res.unwrap_or((None, true))
1996 } else { ((None, true)) }
1999 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, MsgHandleErrInternal> {
2000 let mut channel_state = self.channel_state.lock().unwrap();
2001 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
2003 if chan.get_their_node_id() != *their_node_id {
2004 //TODO: here and below MsgHandleErrInternal, #153 case
2005 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2007 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() })
2008 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
2010 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2013 // we are the origin node and update route information
2014 // also determine if the payment is retryable
2015 if let &HTLCSource::OutboundRoute { .. } = htlc_source {
2016 let (channel_update, _payment_retry) = self.process_onion_failure(htlc_source, msg.reason.data.clone());
2018 // TODO: include pyament_retry info in PaymentFailed event that will be
2019 // fired when receiving revoke_and_ack
2025 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2026 let mut channel_state = self.channel_state.lock().unwrap();
2027 match channel_state.by_id.get_mut(&msg.channel_id) {
2029 if chan.get_their_node_id() != *their_node_id {
2030 //TODO: here and below MsgHandleErrInternal, #153 case
2031 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2033 if (msg.failure_code & 0x8000) != 0 {
2034 return Err(MsgHandleErrInternal::send_err_msg_close_chan("Got update_fail_malformed_htlc with BADONION set", msg.channel_id));
2036 chan.update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() })
2037 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
2040 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2044 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), MsgHandleErrInternal> {
2045 let (revoke_and_ack, commitment_signed, chan_monitor) = {
2046 let mut channel_state = self.channel_state.lock().unwrap();
2047 match channel_state.by_id.get_mut(&msg.channel_id) {
2049 if chan.get_their_node_id() != *their_node_id {
2050 //TODO: here and below MsgHandleErrInternal, #153 case
2051 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2053 chan.commitment_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?
2055 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2058 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2062 Ok((revoke_and_ack, commitment_signed))
2065 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, MsgHandleErrInternal> {
2066 let ((res, mut pending_forwards, mut pending_failures, chan_monitor), short_channel_id) = {
2067 let mut channel_state = self.channel_state.lock().unwrap();
2068 match channel_state.by_id.get_mut(&msg.channel_id) {
2070 if chan.get_their_node_id() != *their_node_id {
2071 //TODO: here and below MsgHandleErrInternal, #153 case
2072 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2074 (chan.revoke_and_ack(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?, chan.get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2076 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2079 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2082 for failure in pending_failures.drain(..) {
2083 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2086 let mut forward_event = None;
2087 if !pending_forwards.is_empty() {
2088 let mut channel_state = self.channel_state.lock().unwrap();
2089 if channel_state.forward_htlcs.is_empty() {
2090 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));
2091 channel_state.next_forward = forward_event.unwrap();
2093 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2094 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2095 hash_map::Entry::Occupied(mut entry) => {
2096 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info });
2098 hash_map::Entry::Vacant(entry) => {
2099 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info }));
2104 match forward_event {
2106 let mut pending_events = self.pending_events.lock().unwrap();
2107 pending_events.push(events::Event::PendingHTLCsForwardable {
2108 time_forwardable: time
2117 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2118 let mut channel_state = self.channel_state.lock().unwrap();
2119 match channel_state.by_id.get_mut(&msg.channel_id) {
2121 if chan.get_their_node_id() != *their_node_id {
2122 //TODO: here and below MsgHandleErrInternal, #153 case
2123 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2125 chan.update_fee(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
2127 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2131 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2132 let (chan_announcement, chan_update) = {
2133 let mut channel_state = self.channel_state.lock().unwrap();
2134 match channel_state.by_id.get_mut(&msg.channel_id) {
2136 if chan.get_their_node_id() != *their_node_id {
2137 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2139 if !chan.is_usable() {
2140 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2143 let our_node_id = self.get_our_node_id();
2144 let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone())
2145 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
2147 let were_node_one = announcement.node_id_1 == our_node_id;
2148 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2149 let bad_sig_action = MsgHandleErrInternal::send_err_msg_close_chan("Bad announcement_signatures node_signature", msg.channel_id);
2150 secp_call!(self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }), bad_sig_action);
2151 secp_call!(self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }), bad_sig_action);
2153 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2155 (msgs::ChannelAnnouncement {
2156 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2157 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2158 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2159 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2160 contents: announcement,
2161 }, self.get_channel_update(chan).unwrap()) // can only fail if we're not in a ready state
2163 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2166 let mut pending_events = self.pending_events.lock().unwrap();
2167 pending_events.push(events::Event::BroadcastChannelAnnouncement { msg: chan_announcement, update_msg: chan_update });
2171 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
2172 let (res, chan_monitor) = {
2173 let mut channel_state = self.channel_state.lock().unwrap();
2174 match channel_state.by_id.get_mut(&msg.channel_id) {
2176 if chan.get_their_node_id() != *their_node_id {
2177 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2179 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
2180 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
2181 (Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
2183 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2186 if let Some(monitor) = chan_monitor {
2187 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2194 /// Begin Update fee process. Allowed only on an outbound channel.
2195 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2196 /// PeerManager::process_events afterwards.
2197 /// Note: This API is likely to change!
2199 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2200 let mut channel_state = self.channel_state.lock().unwrap();
2201 match channel_state.by_id.get_mut(&channel_id) {
2202 None => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2204 if !chan.is_outbound() {
2205 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2207 if !chan.is_live() {
2208 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2210 if let Some((update_fee, commitment_signed, chan_monitor)) = chan.send_update_fee_and_commit(feerate_per_kw).map_err(|e| APIError::APIMisuseError{err: e.err})? {
2211 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2214 let mut pending_events = self.pending_events.lock().unwrap();
2215 pending_events.push(events::Event::UpdateHTLCs {
2216 node_id: chan.get_their_node_id(),
2217 updates: msgs::CommitmentUpdate {
2218 update_add_htlcs: Vec::new(),
2219 update_fulfill_htlcs: Vec::new(),
2220 update_fail_htlcs: Vec::new(),
2221 update_fail_malformed_htlcs: Vec::new(),
2222 update_fee: Some(update_fee),
2233 impl events::EventsProvider for ChannelManager {
2234 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2235 let mut pending_events = self.pending_events.lock().unwrap();
2236 let mut ret = Vec::new();
2237 mem::swap(&mut ret, &mut *pending_events);
2242 impl ChainListener for ChannelManager {
2243 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2244 let mut new_events = Vec::new();
2245 let mut failed_channels = Vec::new();
2247 let mut channel_lock = self.channel_state.lock().unwrap();
2248 let channel_state = channel_lock.borrow_parts();
2249 let short_to_id = channel_state.short_to_id;
2250 channel_state.by_id.retain(|_, channel| {
2251 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2252 if let Ok(Some(funding_locked)) = chan_res {
2253 let announcement_sigs = self.get_announcement_sigs(channel);
2254 new_events.push(events::Event::SendFundingLocked {
2255 node_id: channel.get_their_node_id(),
2256 msg: funding_locked,
2257 announcement_sigs: announcement_sigs
2259 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2260 } else if let Err(e) = chan_res {
2261 new_events.push(events::Event::HandleError {
2262 node_id: channel.get_their_node_id(),
2265 if channel.is_shutdown() {
2269 if let Some(funding_txo) = channel.get_funding_txo() {
2270 for tx in txn_matched {
2271 for inp in tx.input.iter() {
2272 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2273 if let Some(short_id) = channel.get_short_channel_id() {
2274 short_to_id.remove(&short_id);
2276 // It looks like our counterparty went on-chain. We go ahead and
2277 // broadcast our latest local state as well here, just in case its
2278 // some kind of SPV attack, though we expect these to be dropped.
2279 failed_channels.push(channel.force_shutdown());
2280 if let Ok(update) = self.get_channel_update(&channel) {
2281 new_events.push(events::Event::BroadcastChannelUpdate {
2290 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2291 if let Some(short_id) = channel.get_short_channel_id() {
2292 short_to_id.remove(&short_id);
2294 failed_channels.push(channel.force_shutdown());
2295 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2296 // the latest local tx for us, so we should skip that here (it doesn't really
2297 // hurt anything, but does make tests a bit simpler).
2298 failed_channels.last_mut().unwrap().0 = Vec::new();
2299 if let Ok(update) = self.get_channel_update(&channel) {
2300 new_events.push(events::Event::BroadcastChannelUpdate {
2309 for failure in failed_channels.drain(..) {
2310 self.finish_force_close_channel(failure);
2312 let mut pending_events = self.pending_events.lock().unwrap();
2313 for funding_locked in new_events.drain(..) {
2314 pending_events.push(funding_locked);
2316 self.latest_block_height.store(height as usize, Ordering::Release);
2319 /// We force-close the channel without letting our counterparty participate in the shutdown
2320 fn block_disconnected(&self, header: &BlockHeader) {
2321 let mut new_events = Vec::new();
2322 let mut failed_channels = Vec::new();
2324 let mut channel_lock = self.channel_state.lock().unwrap();
2325 let channel_state = channel_lock.borrow_parts();
2326 let short_to_id = channel_state.short_to_id;
2327 channel_state.by_id.retain(|_, v| {
2328 if v.block_disconnected(header) {
2329 if let Some(short_id) = v.get_short_channel_id() {
2330 short_to_id.remove(&short_id);
2332 failed_channels.push(v.force_shutdown());
2333 if let Ok(update) = self.get_channel_update(&v) {
2334 new_events.push(events::Event::BroadcastChannelUpdate {
2344 for failure in failed_channels.drain(..) {
2345 self.finish_force_close_channel(failure);
2347 if !new_events.is_empty() {
2348 let mut pending_events = self.pending_events.lock().unwrap();
2349 for funding_locked in new_events.drain(..) {
2350 pending_events.push(funding_locked);
2353 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2357 macro_rules! handle_error {
2358 ($self: ident, $internal: expr, $their_node_id: expr) => {
2361 Err(MsgHandleErrInternal { err, needs_channel_force_close }) => {
2362 if needs_channel_force_close {
2364 &Some(msgs::ErrorAction::DisconnectPeer { msg: Some(ref msg) }) => {
2365 if msg.channel_id == [0; 32] {
2366 $self.peer_disconnected(&$their_node_id, true);
2368 $self.force_close_channel(&msg.channel_id);
2371 &Some(msgs::ErrorAction::DisconnectPeer { msg: None }) => {},
2372 &Some(msgs::ErrorAction::IgnoreError) => {},
2373 &Some(msgs::ErrorAction::SendErrorMessage { ref msg }) => {
2374 if msg.channel_id == [0; 32] {
2375 $self.peer_disconnected(&$their_node_id, true);
2377 $self.force_close_channel(&msg.channel_id);
2389 impl ChannelMessageHandler for ChannelManager {
2390 //TODO: Handle errors and close channel (or so)
2391 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, HandleError> {
2392 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2395 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2396 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2399 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, HandleError> {
2400 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2403 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2404 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2407 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
2408 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2411 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), HandleError> {
2412 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2415 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, HandleError> {
2416 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2419 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2420 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2423 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2424 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2427 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, HandleError> {
2428 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2431 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2432 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2435 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), HandleError> {
2436 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2439 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, HandleError> {
2440 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2443 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2444 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2447 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2448 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2451 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
2452 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2455 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2456 let mut new_events = Vec::new();
2457 let mut failed_channels = Vec::new();
2458 let mut failed_payments = Vec::new();
2460 let mut channel_state_lock = self.channel_state.lock().unwrap();
2461 let channel_state = channel_state_lock.borrow_parts();
2462 let short_to_id = channel_state.short_to_id;
2463 if no_connection_possible {
2464 channel_state.by_id.retain(|_, chan| {
2465 if chan.get_their_node_id() == *their_node_id {
2466 if let Some(short_id) = chan.get_short_channel_id() {
2467 short_to_id.remove(&short_id);
2469 failed_channels.push(chan.force_shutdown());
2470 if let Ok(update) = self.get_channel_update(&chan) {
2471 new_events.push(events::Event::BroadcastChannelUpdate {
2481 channel_state.by_id.retain(|_, chan| {
2482 if chan.get_their_node_id() == *their_node_id {
2483 //TODO: mark channel disabled (and maybe announce such after a timeout).
2484 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2485 if !failed_adds.is_empty() {
2486 let chan_update = self.get_channel_update(&chan).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
2487 failed_payments.push((chan_update, failed_adds));
2489 if chan.is_shutdown() {
2490 if let Some(short_id) = chan.get_short_channel_id() {
2491 short_to_id.remove(&short_id);
2500 for failure in failed_channels.drain(..) {
2501 self.finish_force_close_channel(failure);
2503 if !new_events.is_empty() {
2504 let mut pending_events = self.pending_events.lock().unwrap();
2505 for event in new_events.drain(..) {
2506 pending_events.push(event);
2509 for (chan_update, mut htlc_sources) in failed_payments {
2510 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2511 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2516 fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<msgs::ChannelReestablish> {
2517 let mut res = Vec::new();
2518 let mut channel_state = self.channel_state.lock().unwrap();
2519 channel_state.by_id.retain(|_, chan| {
2520 if chan.get_their_node_id() == *their_node_id {
2521 if !chan.have_received_message() {
2522 // If we created this (outbound) channel while we were disconnected from the
2523 // peer we probably failed to send the open_channel message, which is now
2524 // lost. We can't have had anything pending related to this channel, so we just
2528 res.push(chan.get_channel_reestablish());
2533 //TODO: Also re-broadcast announcement_signatures
2537 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2538 if msg.channel_id == [0; 32] {
2539 for chan in self.list_channels() {
2540 if chan.remote_network_id == *their_node_id {
2541 self.force_close_channel(&chan.channel_id);
2545 self.force_close_channel(&msg.channel_id);
2552 use chain::chaininterface;
2553 use chain::transaction::OutPoint;
2554 use chain::chaininterface::ChainListener;
2555 use ln::channelmanager::{ChannelManager,OnionKeys};
2556 use ln::channelmonitor::{CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
2557 use ln::router::{Route, RouteHop, Router};
2559 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
2560 use util::test_utils;
2561 use util::events::{Event, EventsProvider};
2562 use util::errors::APIError;
2563 use util::logger::Logger;
2564 use util::ser::Writeable;
2566 use bitcoin::util::hash::Sha256dHash;
2567 use bitcoin::blockdata::block::{Block, BlockHeader};
2568 use bitcoin::blockdata::transaction::{Transaction, TxOut};
2569 use bitcoin::blockdata::constants::genesis_block;
2570 use bitcoin::network::constants::Network;
2571 use bitcoin::network::serialize::serialize;
2572 use bitcoin::network::serialize::BitcoinHash;
2576 use secp256k1::{Secp256k1, Message};
2577 use secp256k1::key::{PublicKey,SecretKey};
2579 use crypto::sha2::Sha256;
2580 use crypto::digest::Digest;
2582 use rand::{thread_rng,Rng};
2584 use std::cell::RefCell;
2585 use std::collections::{BTreeSet, HashMap};
2586 use std::default::Default;
2588 use std::sync::{Arc, Mutex};
2589 use std::sync::atomic::Ordering;
2590 use std::time::Instant;
2593 fn build_test_onion_keys() -> Vec<OnionKeys> {
2594 // Keys from BOLT 4, used in both test vector tests
2595 let secp_ctx = Secp256k1::new();
2600 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
2601 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
2604 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
2605 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
2608 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
2609 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
2612 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
2613 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
2616 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
2617 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
2622 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
2624 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2625 assert_eq!(onion_keys.len(), route.hops.len());
2630 fn onion_vectors() {
2631 // Packet creation test vectors from BOLT 4
2632 let onion_keys = build_test_onion_keys();
2634 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
2635 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
2636 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
2637 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
2638 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
2640 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
2641 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
2642 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
2643 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
2644 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
2646 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
2647 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
2648 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
2649 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
2650 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
2652 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
2653 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
2654 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
2655 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
2656 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
2658 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
2659 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
2660 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
2661 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
2662 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
2664 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
2665 let payloads = vec!(
2666 msgs::OnionHopData {
2668 data: msgs::OnionRealm0HopData {
2669 short_channel_id: 0,
2671 outgoing_cltv_value: 0,
2675 msgs::OnionHopData {
2677 data: msgs::OnionRealm0HopData {
2678 short_channel_id: 0x0101010101010101,
2679 amt_to_forward: 0x0100000001,
2680 outgoing_cltv_value: 0,
2684 msgs::OnionHopData {
2686 data: msgs::OnionRealm0HopData {
2687 short_channel_id: 0x0202020202020202,
2688 amt_to_forward: 0x0200000002,
2689 outgoing_cltv_value: 0,
2693 msgs::OnionHopData {
2695 data: msgs::OnionRealm0HopData {
2696 short_channel_id: 0x0303030303030303,
2697 amt_to_forward: 0x0300000003,
2698 outgoing_cltv_value: 0,
2702 msgs::OnionHopData {
2704 data: msgs::OnionRealm0HopData {
2705 short_channel_id: 0x0404040404040404,
2706 amt_to_forward: 0x0400000004,
2707 outgoing_cltv_value: 0,
2713 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
2714 // Just check the final packet encoding, as it includes all the per-hop vectors in it
2716 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
2720 fn test_failure_packet_onion() {
2721 // Returning Errors test vectors from BOLT 4
2723 let onion_keys = build_test_onion_keys();
2724 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret, 0x2002, &[0; 0]);
2725 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
2727 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret, &onion_error.encode()[..]);
2728 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
2730 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret, &onion_packet_1.data[..]);
2731 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
2733 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret, &onion_packet_2.data[..]);
2734 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
2736 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret, &onion_packet_3.data[..]);
2737 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
2739 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret, &onion_packet_4.data[..]);
2740 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
2743 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
2744 assert!(chain.does_match_tx(tx));
2745 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2746 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
2748 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2749 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
2754 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
2755 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
2756 chan_monitor: Arc<test_utils::TestChannelMonitor>,
2757 node: Arc<ChannelManager>,
2759 network_payment_count: Rc<RefCell<u8>>,
2760 network_chan_count: Rc<RefCell<u32>>,
2762 impl Drop for Node {
2763 fn drop(&mut self) {
2764 if !::std::thread::panicking() {
2765 // Check that we processed all pending events
2766 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
2767 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
2772 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2773 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
2776 fn create_chan_between_nodes_with_value(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2777 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
2778 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
2779 (announcement, as_update, bs_update, channel_id, tx)
2782 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
2783 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
2785 let events_1 = node_a.node.get_and_clear_pending_events();
2786 assert_eq!(events_1.len(), 1);
2787 let accept_chan = match events_1[0] {
2788 Event::SendOpenChannel { ref node_id, ref msg } => {
2789 assert_eq!(*node_id, node_b.node.get_our_node_id());
2790 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), msg).unwrap()
2792 _ => panic!("Unexpected event"),
2795 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_chan).unwrap();
2797 let chan_id = *node_a.network_chan_count.borrow();
2801 let events_2 = node_a.node.get_and_clear_pending_events();
2802 assert_eq!(events_2.len(), 1);
2804 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
2805 assert_eq!(*channel_value_satoshis, channel_value);
2806 assert_eq!(user_channel_id, 42);
2808 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
2809 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
2811 funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
2813 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
2814 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2815 assert_eq!(added_monitors.len(), 1);
2816 assert_eq!(added_monitors[0].0, funding_output);
2817 added_monitors.clear();
2819 _ => panic!("Unexpected event"),
2822 let events_3 = node_a.node.get_and_clear_pending_events();
2823 assert_eq!(events_3.len(), 1);
2824 let funding_signed = match events_3[0] {
2825 Event::SendFundingCreated { ref node_id, ref msg } => {
2826 assert_eq!(*node_id, node_b.node.get_our_node_id());
2827 let res = node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), msg).unwrap();
2828 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
2829 assert_eq!(added_monitors.len(), 1);
2830 assert_eq!(added_monitors[0].0, funding_output);
2831 added_monitors.clear();
2834 _ => panic!("Unexpected event"),
2837 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &funding_signed).unwrap();
2839 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2840 assert_eq!(added_monitors.len(), 1);
2841 assert_eq!(added_monitors[0].0, funding_output);
2842 added_monitors.clear();
2845 let events_4 = node_a.node.get_and_clear_pending_events();
2846 assert_eq!(events_4.len(), 1);
2848 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
2849 assert_eq!(user_channel_id, 42);
2850 assert_eq!(*funding_txo, funding_output);
2852 _ => panic!("Unexpected event"),
2858 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
2859 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
2860 let events_5 = node_b.node.get_and_clear_pending_events();
2861 assert_eq!(events_5.len(), 1);
2863 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2864 assert_eq!(*node_id, node_a.node.get_our_node_id());
2865 assert!(announcement_sigs.is_none());
2866 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), msg).unwrap()
2868 _ => panic!("Unexpected event"),
2873 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
2874 let events_6 = node_a.node.get_and_clear_pending_events();
2875 assert_eq!(events_6.len(), 1);
2876 (match events_6[0] {
2877 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2878 channel_id = msg.channel_id.clone();
2879 assert_eq!(*node_id, node_b.node.get_our_node_id());
2880 (msg.clone(), announcement_sigs.clone().unwrap())
2882 _ => panic!("Unexpected event"),
2886 fn create_chan_between_nodes_with_value_a(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
2887 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
2888 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
2892 fn create_chan_between_nodes_with_value_b(node_a: &Node, node_b: &Node, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
2893 let bs_announcement_sigs = {
2894 let bs_announcement_sigs = node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap().unwrap();
2895 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
2896 bs_announcement_sigs
2899 let events_7 = node_b.node.get_and_clear_pending_events();
2900 assert_eq!(events_7.len(), 1);
2901 let (announcement, bs_update) = match events_7[0] {
2902 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2905 _ => panic!("Unexpected event"),
2908 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
2909 let events_8 = node_a.node.get_and_clear_pending_events();
2910 assert_eq!(events_8.len(), 1);
2911 let as_update = match events_8[0] {
2912 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2913 assert!(*announcement == *msg);
2916 _ => panic!("Unexpected event"),
2919 *node_a.network_chan_count.borrow_mut() += 1;
2921 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
2924 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2925 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
2928 fn create_announced_chan_between_nodes_with_value(nodes: &Vec<Node>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2929 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
2931 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
2932 node.router.handle_channel_update(&chan_announcement.1).unwrap();
2933 node.router.handle_channel_update(&chan_announcement.2).unwrap();
2935 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
2938 macro_rules! check_spends {
2939 ($tx: expr, $spends_tx: expr) => {
2941 let mut funding_tx_map = HashMap::new();
2942 let spends_tx = $spends_tx;
2943 funding_tx_map.insert(spends_tx.txid(), spends_tx);
2944 $tx.verify(&funding_tx_map).unwrap();
2949 fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate) {
2950 let (node_a, broadcaster_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster) } else { (&outbound_node.node, &outbound_node.tx_broadcaster) };
2951 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
2954 node_a.close_channel(channel_id).unwrap();
2955 let events_1 = node_a.get_and_clear_pending_events();
2956 assert_eq!(events_1.len(), 1);
2957 let shutdown_a = match events_1[0] {
2958 Event::SendShutdown { ref node_id, ref msg } => {
2959 assert_eq!(node_id, &node_b.get_our_node_id());
2962 _ => panic!("Unexpected event"),
2965 let (shutdown_b, mut closing_signed_b) = node_b.handle_shutdown(&node_a.get_our_node_id(), &shutdown_a).unwrap();
2966 if !close_inbound_first {
2967 assert!(closing_signed_b.is_none());
2969 let (empty_a, mut closing_signed_a) = node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b.unwrap()).unwrap();
2970 assert!(empty_a.is_none());
2971 if close_inbound_first {
2972 assert!(closing_signed_a.is_none());
2973 closing_signed_a = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2974 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2975 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2977 let empty_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2978 assert!(empty_b.is_none());
2979 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2980 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2982 closing_signed_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2983 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2984 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2986 let empty_a2 = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2987 assert!(empty_a2.is_none());
2988 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2989 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2991 assert_eq!(tx_a, tx_b);
2992 check_spends!(tx_a, funding_tx);
2994 let events_2 = node_a.get_and_clear_pending_events();
2995 assert_eq!(events_2.len(), 1);
2996 let as_update = match events_2[0] {
2997 Event::BroadcastChannelUpdate { ref msg } => {
3000 _ => panic!("Unexpected event"),
3003 let events_3 = node_b.get_and_clear_pending_events();
3004 assert_eq!(events_3.len(), 1);
3005 let bs_update = match events_3[0] {
3006 Event::BroadcastChannelUpdate { ref msg } => {
3009 _ => panic!("Unexpected event"),
3012 (as_update, bs_update)
3017 msgs: Vec<msgs::UpdateAddHTLC>,
3018 commitment_msg: msgs::CommitmentSigned,
3021 fn from_event(event: Event) -> SendEvent {
3023 Event::UpdateHTLCs { node_id, updates: msgs::CommitmentUpdate { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => {
3024 assert!(update_fulfill_htlcs.is_empty());
3025 assert!(update_fail_htlcs.is_empty());
3026 assert!(update_fail_malformed_htlcs.is_empty());
3027 assert!(update_fee.is_none());
3028 SendEvent { node_id: node_id, msgs: update_add_htlcs, commitment_msg: commitment_signed }
3030 _ => panic!("Unexpected event type!"),
3035 macro_rules! check_added_monitors {
3036 ($node: expr, $count: expr) => {
3038 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3039 assert_eq!(added_monitors.len(), $count);
3040 added_monitors.clear();
3045 macro_rules! commitment_signed_dance {
3046 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3048 check_added_monitors!($node_a, 0);
3049 let (as_revoke_and_ack, as_commitment_signed) = $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3050 check_added_monitors!($node_a, 1);
3051 check_added_monitors!($node_b, 0);
3052 assert!($node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
3053 check_added_monitors!($node_b, 1);
3054 let (bs_revoke_and_ack, bs_none) = $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
3055 assert!(bs_none.is_none());
3056 check_added_monitors!($node_b, 1);
3057 if $fail_backwards {
3058 assert!($node_a.node.get_and_clear_pending_events().is_empty());
3060 assert!($node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
3062 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3063 if $fail_backwards {
3064 assert_eq!(added_monitors.len(), 2);
3065 assert!(added_monitors[0].0 != added_monitors[1].0);
3067 assert_eq!(added_monitors.len(), 1);
3069 added_monitors.clear();
3075 macro_rules! get_payment_preimage_hash {
3078 let payment_preimage = [*$node.network_payment_count.borrow(); 32];
3079 *$node.network_payment_count.borrow_mut() += 1;
3080 let mut payment_hash = [0; 32];
3081 let mut sha = Sha256::new();
3082 sha.input(&payment_preimage[..]);
3083 sha.result(&mut payment_hash);
3084 (payment_preimage, payment_hash)
3089 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3090 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3092 let mut payment_event = {
3093 origin_node.node.send_payment(route, our_payment_hash).unwrap();
3094 check_added_monitors!(origin_node, 1);
3096 let mut events = origin_node.node.get_and_clear_pending_events();
3097 assert_eq!(events.len(), 1);
3098 SendEvent::from_event(events.remove(0))
3100 let mut prev_node = origin_node;
3102 for (idx, &node) in expected_route.iter().enumerate() {
3103 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
3105 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3106 check_added_monitors!(node, 0);
3107 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
3109 let events_1 = node.node.get_and_clear_pending_events();
3110 assert_eq!(events_1.len(), 1);
3112 Event::PendingHTLCsForwardable { .. } => { },
3113 _ => panic!("Unexpected event"),
3116 node.node.channel_state.lock().unwrap().next_forward = Instant::now();
3117 node.node.process_pending_htlc_forwards();
3119 let mut events_2 = node.node.get_and_clear_pending_events();
3120 assert_eq!(events_2.len(), 1);
3121 if idx == expected_route.len() - 1 {
3123 Event::PaymentReceived { ref payment_hash, amt } => {
3124 assert_eq!(our_payment_hash, *payment_hash);
3125 assert_eq!(amt, recv_value);
3127 _ => panic!("Unexpected event"),
3130 check_added_monitors!(node, 1);
3131 payment_event = SendEvent::from_event(events_2.remove(0));
3132 assert_eq!(payment_event.msgs.len(), 1);
3138 (our_payment_preimage, our_payment_hash)
3141 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
3142 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
3143 check_added_monitors!(expected_route.last().unwrap(), 1);
3145 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
3146 macro_rules! update_fulfill_dance {
3147 ($node: expr, $prev_node: expr, $last_node: expr) => {
3149 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3151 check_added_monitors!($node, 0);
3153 check_added_monitors!($node, 1);
3155 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
3160 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3161 let mut prev_node = expected_route.last().unwrap();
3162 for (idx, node) in expected_route.iter().rev().enumerate() {
3163 assert_eq!(expected_next_node, node.node.get_our_node_id());
3164 if next_msgs.is_some() {
3165 update_fulfill_dance!(node, prev_node, false);
3168 let events = node.node.get_and_clear_pending_events();
3169 if !skip_last || idx != expected_route.len() - 1 {
3170 assert_eq!(events.len(), 1);
3172 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 update_fee, ref commitment_signed } } => {
3173 assert!(update_add_htlcs.is_empty());
3174 assert_eq!(update_fulfill_htlcs.len(), 1);
3175 assert!(update_fail_htlcs.is_empty());
3176 assert!(update_fail_malformed_htlcs.is_empty());
3177 assert!(update_fee.is_none());
3178 expected_next_node = node_id.clone();
3179 next_msgs = Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()));
3181 _ => panic!("Unexpected event"),
3184 assert!(events.is_empty());
3186 if !skip_last && idx == expected_route.len() - 1 {
3187 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3194 update_fulfill_dance!(origin_node, expected_route.first().unwrap(), true);
3195 let events = origin_node.node.get_and_clear_pending_events();
3196 assert_eq!(events.len(), 1);
3198 Event::PaymentSent { payment_preimage } => {
3199 assert_eq!(payment_preimage, our_payment_preimage);
3201 _ => panic!("Unexpected event"),
3206 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
3207 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
3210 const TEST_FINAL_CLTV: u32 = 32;
3212 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3213 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();
3214 assert_eq!(route.hops.len(), expected_route.len());
3215 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3216 assert_eq!(hop.pubkey, node.node.get_our_node_id());
3219 send_along_route(origin_node, route, expected_route, recv_value)
3222 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
3223 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();
3224 assert_eq!(route.hops.len(), expected_route.len());
3225 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3226 assert_eq!(hop.pubkey, node.node.get_our_node_id());
3229 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3231 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
3233 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
3234 _ => panic!("Unknown error variants"),
3238 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
3239 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
3240 claim_payment(&origin, expected_route, our_payment_preimage);
3243 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
3244 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
3245 check_added_monitors!(expected_route.last().unwrap(), 1);
3247 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
3248 macro_rules! update_fail_dance {
3249 ($node: expr, $prev_node: expr, $last_node: expr) => {
3251 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3252 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
3257 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3258 let mut prev_node = expected_route.last().unwrap();
3259 for (idx, node) in expected_route.iter().rev().enumerate() {
3260 assert_eq!(expected_next_node, node.node.get_our_node_id());
3261 if next_msgs.is_some() {
3262 // We may be the "last node" for the purpose of the commitment dance if we're
3263 // skipping the last node (implying it is disconnected) and we're the
3264 // second-to-last node!
3265 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
3268 let events = node.node.get_and_clear_pending_events();
3269 if !skip_last || idx != expected_route.len() - 1 {
3270 assert_eq!(events.len(), 1);
3272 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 update_fee, ref commitment_signed } } => {
3273 assert!(update_add_htlcs.is_empty());
3274 assert!(update_fulfill_htlcs.is_empty());
3275 assert_eq!(update_fail_htlcs.len(), 1);
3276 assert!(update_fail_malformed_htlcs.is_empty());
3277 assert!(update_fee.is_none());
3278 expected_next_node = node_id.clone();
3279 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
3281 _ => panic!("Unexpected event"),
3284 assert!(events.is_empty());
3286 if !skip_last && idx == expected_route.len() - 1 {
3287 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3294 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
3296 let events = origin_node.node.get_and_clear_pending_events();
3297 assert_eq!(events.len(), 1);
3299 Event::PaymentFailed { payment_hash } => {
3300 assert_eq!(payment_hash, our_payment_hash);
3302 _ => panic!("Unexpected event"),
3307 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
3308 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
3311 fn create_network(node_count: usize) -> Vec<Node> {
3312 let mut nodes = Vec::new();
3313 let mut rng = thread_rng();
3314 let secp_ctx = Secp256k1::new();
3315 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
3317 let chan_count = Rc::new(RefCell::new(0));
3318 let payment_count = Rc::new(RefCell::new(0));
3320 for _ in 0..node_count {
3321 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
3322 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
3323 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
3324 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
3326 let mut key_slice = [0; 32];
3327 rng.fill_bytes(&mut key_slice);
3328 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
3330 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();
3331 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
3332 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router,
3333 network_payment_count: payment_count.clone(),
3334 network_chan_count: chan_count.clone(),
3342 fn test_async_inbound_update_fee() {
3343 let mut nodes = create_network(2);
3344 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3345 let channel_id = chan.2;
3347 macro_rules! get_feerate {
3349 let chan_lock = $node.node.channel_state.lock().unwrap();
3350 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3356 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3360 // send (1) commitment_signed -.
3361 // <- update_add_htlc/commitment_signed
3362 // send (2) RAA (awaiting remote revoke) -.
3363 // (1) commitment_signed is delivered ->
3364 // .- send (3) RAA (awaiting remote revoke)
3365 // (2) RAA is delivered ->
3366 // .- send (4) commitment_signed
3367 // <- (3) RAA is delivered
3368 // send (5) commitment_signed -.
3369 // <- (4) commitment_signed is delivered
3371 // (5) commitment_signed is delivered ->
3373 // (6) RAA is delivered ->
3375 // First nodes[0] generates an update_fee
3376 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3377 check_added_monitors!(nodes[0], 1);
3379 let events_0 = nodes[0].node.get_and_clear_pending_events();
3380 assert_eq!(events_0.len(), 1);
3381 let (update_msg, commitment_signed) = match events_0[0] { // (1)
3382 Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3383 (update_fee.as_ref(), commitment_signed)
3385 _ => panic!("Unexpected event"),
3388 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3390 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3391 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3392 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
3393 check_added_monitors!(nodes[1], 1);
3395 let payment_event = {
3396 let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3397 assert_eq!(events_1.len(), 1);
3398 SendEvent::from_event(events_1.remove(0))
3400 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3401 assert_eq!(payment_event.msgs.len(), 1);
3403 // ...now when the messages get delivered everyone should be happy
3404 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3405 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
3406 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3407 check_added_monitors!(nodes[0], 1);
3409 // deliver(1), generate (3):
3410 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3411 assert!(bs_commitment_signed.is_none()); // nodes[1] is awaiting nodes[0] revoke_and_ack
3412 check_added_monitors!(nodes[1], 1);
3414 let bs_update = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
3415 assert!(bs_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (4)
3416 assert!(bs_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (4)
3417 assert!(bs_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (4)
3418 assert!(bs_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (4)
3419 assert!(bs_update.as_ref().unwrap().update_fee.is_none()); // (4)
3420 check_added_monitors!(nodes[1], 1);
3422 let as_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap(); // deliver (3)
3423 assert!(as_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (5)
3424 assert!(as_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (5)
3425 assert!(as_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (5)
3426 assert!(as_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (5)
3427 assert!(as_update.as_ref().unwrap().update_fee.is_none()); // (5)
3428 check_added_monitors!(nodes[0], 1);
3430 let (as_second_revoke, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.unwrap().commitment_signed).unwrap(); // deliver (4)
3431 assert!(as_second_commitment_signed.is_none()); // only (6)
3432 check_added_monitors!(nodes[0], 1);
3434 let (bs_second_revoke, bs_second_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.unwrap().commitment_signed).unwrap(); // deliver (5)
3435 assert!(bs_second_commitment_signed.is_none());
3436 check_added_monitors!(nodes[1], 1);
3438 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3439 check_added_monitors!(nodes[0], 1);
3441 let events_2 = nodes[0].node.get_and_clear_pending_events();
3442 assert_eq!(events_2.len(), 1);
3444 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
3445 _ => panic!("Unexpected event"),
3448 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none()); // deliver (6)
3449 check_added_monitors!(nodes[1], 1);
3453 fn test_update_fee_unordered_raa() {
3454 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
3455 // crash in an earlier version of the update_fee patch)
3456 let mut nodes = create_network(2);
3457 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3458 let channel_id = chan.2;
3460 macro_rules! get_feerate {
3462 let chan_lock = $node.node.channel_state.lock().unwrap();
3463 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3469 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3471 // First nodes[0] generates an update_fee
3472 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3473 check_added_monitors!(nodes[0], 1);
3475 let events_0 = nodes[0].node.get_and_clear_pending_events();
3476 assert_eq!(events_0.len(), 1);
3477 let update_msg = match events_0[0] { // (1)
3478 Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
3481 _ => panic!("Unexpected event"),
3484 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3486 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3487 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3488 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
3489 check_added_monitors!(nodes[1], 1);
3491 let payment_event = {
3492 let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3493 assert_eq!(events_1.len(), 1);
3494 SendEvent::from_event(events_1.remove(0))
3496 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3497 assert_eq!(payment_event.msgs.len(), 1);
3499 // ...now when the messages get delivered everyone should be happy
3500 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3501 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
3502 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3503 check_added_monitors!(nodes[0], 1);
3505 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none()); // deliver (2)
3506 check_added_monitors!(nodes[1], 1);
3508 // We can't continue, sadly, because our (1) now has a bogus signature
3512 fn test_multi_flight_update_fee() {
3513 let nodes = create_network(2);
3514 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3515 let channel_id = chan.2;
3517 macro_rules! get_feerate {
3519 let chan_lock = $node.node.channel_state.lock().unwrap();
3520 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3526 // update_fee/commitment_signed ->
3527 // .- send (1) RAA and (2) commitment_signed
3528 // update_fee (never committed) ->
3529 // (3) update_fee ->
3530 // We have to manually generate the above update_fee, it is allowed by the protocol but we
3531 // don't track which updates correspond to which revoke_and_ack responses so we're in
3532 // AwaitingRAA mode and will not generate the update_fee yet.
3533 // <- (1) RAA delivered
3534 // (3) is generated and send (4) CS -.
3535 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
3536 // know the per_commitment_point to use for it.
3537 // <- (2) commitment_signed delivered
3538 // revoke_and_ack ->
3539 // B should send no response here
3540 // (4) commitment_signed delivered ->
3541 // <- RAA/commitment_signed delivered
3542 // revoke_and_ack ->
3544 // First nodes[0] generates an update_fee
3545 let initial_feerate = get_feerate!(nodes[0]);
3546 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
3547 check_added_monitors!(nodes[0], 1);
3549 let events_0 = nodes[0].node.get_and_clear_pending_events();
3550 assert_eq!(events_0.len(), 1);
3551 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
3552 Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3553 (update_fee.as_ref().unwrap(), commitment_signed)
3555 _ => panic!("Unexpected event"),
3558 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
3559 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
3560 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
3561 check_added_monitors!(nodes[1], 1);
3563 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
3565 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
3566 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3568 // Create the (3) update_fee message that nodes[0] will generate before it does...
3569 let mut update_msg_2 = msgs::UpdateFee {
3570 channel_id: update_msg_1.channel_id.clone(),
3571 feerate_per_kw: (initial_feerate + 30) as u32,
3574 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3576 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
3578 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3580 // Deliver (1), generating (3) and (4)
3581 let as_second_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
3582 check_added_monitors!(nodes[0], 1);
3583 assert!(as_second_update.as_ref().unwrap().update_add_htlcs.is_empty());
3584 assert!(as_second_update.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3585 assert!(as_second_update.as_ref().unwrap().update_fail_htlcs.is_empty());
3586 assert!(as_second_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3587 // Check that the update_fee newly generated matches what we delivered:
3588 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
3589 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
3591 // Deliver (2) commitment_signed
3592 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), bs_commitment_signed.as_ref().unwrap()).unwrap();
3593 check_added_monitors!(nodes[0], 1);
3594 assert!(as_commitment_signed.is_none());
3596 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none());
3597 check_added_monitors!(nodes[1], 1);
3600 let (bs_second_revoke, bs_second_commitment) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.unwrap().commitment_signed).unwrap();
3601 check_added_monitors!(nodes[1], 1);
3603 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3604 check_added_monitors!(nodes[0], 1);
3606 let (as_second_revoke, as_second_commitment) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment.unwrap()).unwrap();
3607 assert!(as_second_commitment.is_none());
3608 check_added_monitors!(nodes[0], 1);
3610 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none());
3611 check_added_monitors!(nodes[1], 1);
3615 fn test_update_fee_vanilla() {
3616 let nodes = create_network(2);
3617 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3618 let channel_id = chan.2;
3620 macro_rules! get_feerate {
3622 let chan_lock = $node.node.channel_state.lock().unwrap();
3623 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3628 let feerate = get_feerate!(nodes[0]);
3629 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3631 let events_0 = nodes[0].node.get_and_clear_pending_events();
3632 assert_eq!(events_0.len(), 1);
3633 let (update_msg, commitment_signed) = match events_0[0] {
3634 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3635 (update_fee.as_ref(), commitment_signed)
3637 _ => panic!("Unexpected event"),
3639 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3641 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3642 let commitment_signed = commitment_signed.unwrap();
3643 check_added_monitors!(nodes[0], 1);
3644 check_added_monitors!(nodes[1], 1);
3646 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3647 assert!(resp_option.is_none());
3648 check_added_monitors!(nodes[0], 1);
3650 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3651 assert!(commitment_signed.is_none());
3652 check_added_monitors!(nodes[0], 1);
3654 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3655 assert!(resp_option.is_none());
3656 check_added_monitors!(nodes[1], 1);
3660 fn test_update_fee_with_fundee_update_add_htlc() {
3661 let mut nodes = create_network(2);
3662 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3663 let channel_id = chan.2;
3665 macro_rules! get_feerate {
3667 let chan_lock = $node.node.channel_state.lock().unwrap();
3668 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3674 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3676 let feerate = get_feerate!(nodes[0]);
3677 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3679 let events_0 = nodes[0].node.get_and_clear_pending_events();
3680 assert_eq!(events_0.len(), 1);
3681 let (update_msg, commitment_signed) = match events_0[0] {
3682 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3683 (update_fee.as_ref(), commitment_signed)
3685 _ => panic!("Unexpected event"),
3687 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3688 check_added_monitors!(nodes[0], 1);
3689 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3690 let commitment_signed = commitment_signed.unwrap();
3691 check_added_monitors!(nodes[1], 1);
3693 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
3695 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
3697 // nothing happens since node[1] is in AwaitingRemoteRevoke
3698 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
3700 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
3701 assert_eq!(added_monitors.len(), 0);
3702 added_monitors.clear();
3704 let events = nodes[0].node.get_and_clear_pending_events();
3705 assert_eq!(events.len(), 0);
3706 // node[1] has nothing to do
3708 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3709 assert!(resp_option.is_none());
3710 check_added_monitors!(nodes[0], 1);
3712 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3713 assert!(commitment_signed.is_none());
3714 check_added_monitors!(nodes[0], 1);
3715 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3716 // AwaitingRemoteRevoke ends here
3718 let commitment_update = resp_option.unwrap();
3719 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
3720 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
3721 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
3722 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
3723 assert_eq!(commitment_update.update_fee.is_none(), true);
3725 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
3726 let (revoke, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3727 check_added_monitors!(nodes[0], 1);
3728 check_added_monitors!(nodes[1], 1);
3729 let commitment_signed = commitment_signed.unwrap();
3730 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
3731 check_added_monitors!(nodes[1], 1);
3732 assert!(resp_option.is_none());
3734 let (revoke, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
3735 check_added_monitors!(nodes[1], 1);
3736 assert!(commitment_signed.is_none());
3737 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
3738 check_added_monitors!(nodes[0], 1);
3739 assert!(resp_option.is_none());
3741 let events = nodes[0].node.get_and_clear_pending_events();
3742 assert_eq!(events.len(), 1);
3744 Event::PendingHTLCsForwardable { .. } => { },
3745 _ => panic!("Unexpected event"),
3747 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
3748 nodes[0].node.process_pending_htlc_forwards();
3750 let events = nodes[0].node.get_and_clear_pending_events();
3751 assert_eq!(events.len(), 1);
3753 Event::PaymentReceived { .. } => { },
3754 _ => panic!("Unexpected event"),
3757 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
3759 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
3760 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
3761 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3765 fn test_update_fee() {
3766 let nodes = create_network(2);
3767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3768 let channel_id = chan.2;
3770 macro_rules! get_feerate {
3772 let chan_lock = $node.node.channel_state.lock().unwrap();
3773 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3779 // (1) update_fee/commitment_signed ->
3780 // <- (2) revoke_and_ack
3781 // .- send (3) commitment_signed
3782 // (4) update_fee/commitment_signed ->
3783 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
3784 // <- (3) commitment_signed delivered
3785 // send (6) revoke_and_ack -.
3786 // <- (5) deliver revoke_and_ack
3787 // (6) deliver revoke_and_ack ->
3788 // .- send (7) commitment_signed in response to (4)
3789 // <- (7) deliver commitment_signed
3790 // revoke_and_ack ->
3792 // Create and deliver (1)...
3793 let feerate = get_feerate!(nodes[0]);
3794 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3796 let events_0 = nodes[0].node.get_and_clear_pending_events();
3797 assert_eq!(events_0.len(), 1);
3798 let (update_msg, commitment_signed) = match events_0[0] {
3799 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3800 (update_fee.as_ref(), commitment_signed)
3802 _ => panic!("Unexpected event"),
3804 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3806 // Generate (2) and (3):
3807 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3808 let commitment_signed_0 = commitment_signed.unwrap();
3809 check_added_monitors!(nodes[0], 1);
3810 check_added_monitors!(nodes[1], 1);
3813 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3814 assert!(resp_option.is_none());
3815 check_added_monitors!(nodes[0], 1);
3817 // Create and deliver (4)...
3818 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
3819 let events_0 = nodes[0].node.get_and_clear_pending_events();
3820 assert_eq!(events_0.len(), 1);
3821 let (update_msg, commitment_signed) = match events_0[0] {
3822 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3823 (update_fee.as_ref(), commitment_signed)
3825 _ => panic!("Unexpected event"),
3827 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3829 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3831 assert!(commitment_signed.is_none());
3832 check_added_monitors!(nodes[0], 1);
3833 check_added_monitors!(nodes[1], 1);
3835 // Handle (3), creating (6):
3836 let (revoke_msg_0, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
3837 assert!(commitment_signed.is_none());
3838 check_added_monitors!(nodes[0], 1);
3841 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3842 assert!(resp_option.is_none());
3843 check_added_monitors!(nodes[0], 1);
3845 // Deliver (6), creating (7):
3846 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
3847 let commitment_signed = resp_option.unwrap().commitment_signed;
3848 check_added_monitors!(nodes[1], 1);
3851 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3852 assert!(commitment_signed.is_none());
3853 check_added_monitors!(nodes[0], 1);
3854 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3855 assert!(resp_option.is_none());
3856 check_added_monitors!(nodes[1], 1);
3858 assert_eq!(get_feerate!(nodes[0]), feerate + 30);
3859 assert_eq!(get_feerate!(nodes[1]), feerate + 30);
3860 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3864 fn fake_network_test() {
3865 // Simple test which builds a network of ChannelManagers, connects them to each other, and
3866 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
3867 let nodes = create_network(4);
3869 // Create some initial channels
3870 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3871 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3872 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
3874 // Rebalance the network a bit by relaying one payment through all the channels...
3875 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3876 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3877 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3878 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3880 // Send some more payments
3881 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
3882 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
3883 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
3885 // Test failure packets
3886 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
3887 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
3889 // Add a new channel that skips 3
3890 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
3892 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
3893 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
3894 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3895 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3896 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3897 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3898 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3900 // Do some rebalance loop payments, simultaneously
3901 let mut hops = Vec::with_capacity(3);
3902 hops.push(RouteHop {
3903 pubkey: nodes[2].node.get_our_node_id(),
3904 short_channel_id: chan_2.0.contents.short_channel_id,
3906 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
3908 hops.push(RouteHop {
3909 pubkey: nodes[3].node.get_our_node_id(),
3910 short_channel_id: chan_3.0.contents.short_channel_id,
3912 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
3914 hops.push(RouteHop {
3915 pubkey: nodes[1].node.get_our_node_id(),
3916 short_channel_id: chan_4.0.contents.short_channel_id,
3918 cltv_expiry_delta: TEST_FINAL_CLTV,
3920 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;
3921 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;
3922 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
3924 let mut hops = Vec::with_capacity(3);
3925 hops.push(RouteHop {
3926 pubkey: nodes[3].node.get_our_node_id(),
3927 short_channel_id: chan_4.0.contents.short_channel_id,
3929 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
3931 hops.push(RouteHop {
3932 pubkey: nodes[2].node.get_our_node_id(),
3933 short_channel_id: chan_3.0.contents.short_channel_id,
3935 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
3937 hops.push(RouteHop {
3938 pubkey: nodes[1].node.get_our_node_id(),
3939 short_channel_id: chan_2.0.contents.short_channel_id,
3941 cltv_expiry_delta: TEST_FINAL_CLTV,
3943 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;
3944 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;
3945 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
3947 // Claim the rebalances...
3948 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
3949 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
3951 // Add a duplicate new channel from 2 to 4
3952 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
3954 // Send some payments across both channels
3955 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3956 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3957 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3959 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
3961 //TODO: Test that routes work again here as we've been notified that the channel is full
3963 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
3964 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
3965 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
3967 // Close down the channels...
3968 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
3969 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
3970 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
3971 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
3972 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
3976 fn duplicate_htlc_test() {
3977 // Test that we accept duplicate payment_hash HTLCs across the network and that
3978 // claiming/failing them are all separate and don't effect each other
3979 let mut nodes = create_network(6);
3981 // Create some initial channels to route via 3 to 4/5 from 0/1/2
3982 create_announced_chan_between_nodes(&nodes, 0, 3);
3983 create_announced_chan_between_nodes(&nodes, 1, 3);
3984 create_announced_chan_between_nodes(&nodes, 2, 3);
3985 create_announced_chan_between_nodes(&nodes, 3, 4);
3986 create_announced_chan_between_nodes(&nodes, 3, 5);
3988 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
3990 *nodes[0].network_payment_count.borrow_mut() -= 1;
3991 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
3993 *nodes[0].network_payment_count.borrow_mut() -= 1;
3994 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
3996 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
3997 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
3998 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
4001 #[derive(PartialEq)]
4002 enum HTLCType { NONE, TIMEOUT, SUCCESS }
4003 /// Tests that the given node has broadcast transactions for the given Channel
4005 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
4006 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
4007 /// broadcast and the revoked outputs were claimed.
4009 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
4010 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
4012 /// All broadcast transactions must be accounted for in one of the above three types of we'll
4014 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
4015 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4016 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
4018 let mut res = Vec::with_capacity(2);
4019 node_txn.retain(|tx| {
4020 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
4021 check_spends!(tx, chan.3.clone());
4022 if commitment_tx.is_none() {
4023 res.push(tx.clone());
4028 if let Some(explicit_tx) = commitment_tx {
4029 res.push(explicit_tx.clone());
4032 assert_eq!(res.len(), 1);
4034 if has_htlc_tx != HTLCType::NONE {
4035 node_txn.retain(|tx| {
4036 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
4037 check_spends!(tx, res[0].clone());
4038 if has_htlc_tx == HTLCType::TIMEOUT {
4039 assert!(tx.lock_time != 0);
4041 assert!(tx.lock_time == 0);
4043 res.push(tx.clone());
4047 assert_eq!(res.len(), 2);
4050 assert!(node_txn.is_empty());
4054 /// Tests that the given node has broadcast a claim transaction against the provided revoked
4055 /// HTLC transaction.
4056 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
4057 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4058 assert_eq!(node_txn.len(), 1);
4059 node_txn.retain(|tx| {
4060 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
4061 check_spends!(tx, revoked_tx.clone());
4065 assert!(node_txn.is_empty());
4068 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
4069 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4071 assert!(node_txn.len() >= 1);
4072 assert_eq!(node_txn[0].input.len(), 1);
4073 let mut found_prev = false;
4075 for tx in prev_txn {
4076 if node_txn[0].input[0].previous_output.txid == tx.txid() {
4077 check_spends!(node_txn[0], tx.clone());
4078 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
4079 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
4085 assert!(found_prev);
4087 let mut res = Vec::new();
4088 mem::swap(&mut *node_txn, &mut res);
4092 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
4093 let events_1 = nodes[a].node.get_and_clear_pending_events();
4094 assert_eq!(events_1.len(), 1);
4095 let as_update = match events_1[0] {
4096 Event::BroadcastChannelUpdate { ref msg } => {
4099 _ => panic!("Unexpected event"),
4102 let events_2 = nodes[b].node.get_and_clear_pending_events();
4103 assert_eq!(events_2.len(), 1);
4104 let bs_update = match events_2[0] {
4105 Event::BroadcastChannelUpdate { ref msg } => {
4108 _ => panic!("Unexpected event"),
4112 node.router.handle_channel_update(&as_update).unwrap();
4113 node.router.handle_channel_update(&bs_update).unwrap();
4118 fn channel_reserve_test() {
4120 use std::sync::atomic::Ordering;
4121 use ln::msgs::HandleError;
4123 macro_rules! get_channel_value_stat {
4124 ($node: expr, $channel_id: expr) => {{
4125 let chan_lock = $node.node.channel_state.lock().unwrap();
4126 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
4127 chan.get_value_stat()
4131 let mut nodes = create_network(3);
4132 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
4133 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
4135 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
4136 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
4138 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
4139 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
4141 macro_rules! get_route_and_payment_hash {
4142 ($recv_value: expr) => {{
4143 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
4144 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4145 (route, payment_hash, payment_preimage)
4149 macro_rules! expect_pending_htlcs_forwardable {
4151 let events = $node.node.get_and_clear_pending_events();
4152 assert_eq!(events.len(), 1);
4154 Event::PendingHTLCsForwardable { .. } => { },
4155 _ => panic!("Unexpected event"),
4157 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4158 $node.node.process_pending_htlc_forwards();
4162 macro_rules! expect_forward {
4164 let mut events = $node.node.get_and_clear_pending_events();
4165 assert_eq!(events.len(), 1);
4166 check_added_monitors!($node, 1);
4167 let payment_event = SendEvent::from_event(events.remove(0));
4172 macro_rules! expect_payment_received {
4173 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
4174 let events = $node.node.get_and_clear_pending_events();
4175 assert_eq!(events.len(), 1);
4177 Event::PaymentReceived { ref payment_hash, amt } => {
4178 assert_eq!($expected_payment_hash, *payment_hash);
4179 assert_eq!($expected_recv_value, amt);
4181 _ => panic!("Unexpected event"),
4186 let feemsat = 239; // somehow we know?
4187 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
4189 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
4191 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
4193 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
4194 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
4195 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
4197 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4198 _ => panic!("Unknown error variants"),
4202 let mut htlc_id = 0;
4203 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
4204 // nodes[0]'s wealth
4206 let amt_msat = recv_value_0 + total_fee_msat;
4207 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
4210 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
4213 let (stat01_, stat11_, stat12_, stat22_) = (
4214 get_channel_value_stat!(nodes[0], chan_1.2),
4215 get_channel_value_stat!(nodes[1], chan_1.2),
4216 get_channel_value_stat!(nodes[1], chan_2.2),
4217 get_channel_value_stat!(nodes[2], chan_2.2),
4220 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
4221 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
4222 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
4223 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
4224 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
4228 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
4229 // attempt to get channel_reserve violation
4230 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
4231 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
4233 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4234 _ => panic!("Unknown error variants"),
4238 // adding pending output
4239 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
4240 let amt_msat_1 = recv_value_1 + total_fee_msat;
4242 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
4243 let payment_event_1 = {
4244 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
4245 check_added_monitors!(nodes[0], 1);
4247 let mut events = nodes[0].node.get_and_clear_pending_events();
4248 assert_eq!(events.len(), 1);
4249 SendEvent::from_event(events.remove(0))
4251 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
4253 // channel reserve test with htlc pending output > 0
4254 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
4256 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4257 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4258 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4259 _ => panic!("Unknown error variants"),
4264 // test channel_reserve test on nodes[1] side
4265 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4267 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
4268 let secp_ctx = Secp256k1::new();
4269 let session_priv = SecretKey::from_slice(&secp_ctx, &{
4270 let mut session_key = [0; 32];
4271 rng::fill_bytes(&mut session_key);
4273 }).expect("RNG is bad!");
4275 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4276 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
4277 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
4278 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
4279 let msg = msgs::UpdateAddHTLC {
4280 channel_id: chan_1.2,
4282 amount_msat: htlc_msat,
4283 payment_hash: our_payment_hash,
4284 cltv_expiry: htlc_cltv,
4285 onion_routing_packet: onion_packet,
4288 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
4290 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
4294 // split the rest to test holding cell
4295 let recv_value_21 = recv_value_2/2;
4296 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
4298 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
4299 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat), stat.channel_reserve_msat);
4302 // now see if they go through on both sides
4303 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
4304 // but this will stuck in the holding cell
4305 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
4306 check_added_monitors!(nodes[0], 0);
4307 let events = nodes[0].node.get_and_clear_pending_events();
4308 assert_eq!(events.len(), 0);
4310 // test with outbound holding cell amount > 0
4312 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
4313 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4314 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4315 _ => panic!("Unknown error variants"),
4319 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
4320 // this will also stuck in the holding cell
4321 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
4322 check_added_monitors!(nodes[0], 0);
4323 let events = nodes[0].node.get_and_clear_pending_events();
4324 assert_eq!(events.len(), 0);
4326 // flush the pending htlc
4327 let (as_revoke_and_ack, as_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
4328 check_added_monitors!(nodes[1], 1);
4330 let commitment_update_2 = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap().unwrap();
4331 check_added_monitors!(nodes[0], 1);
4332 let (bs_revoke_and_ack, bs_none) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
4333 assert!(bs_none.is_none());
4334 check_added_monitors!(nodes[0], 1);
4335 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
4336 check_added_monitors!(nodes[1], 1);
4338 expect_pending_htlcs_forwardable!(nodes[1]);
4340 let ref payment_event_11 = expect_forward!(nodes[1]);
4341 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
4342 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
4344 expect_pending_htlcs_forwardable!(nodes[2]);
4345 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
4347 // flush the htlcs in the holding cell
4348 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
4349 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
4350 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
4351 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
4352 expect_pending_htlcs_forwardable!(nodes[1]);
4354 let ref payment_event_3 = expect_forward!(nodes[1]);
4355 assert_eq!(payment_event_3.msgs.len(), 2);
4356 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
4357 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
4359 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
4360 expect_pending_htlcs_forwardable!(nodes[2]);
4362 let events = nodes[2].node.get_and_clear_pending_events();
4363 assert_eq!(events.len(), 2);
4365 Event::PaymentReceived { ref payment_hash, amt } => {
4366 assert_eq!(our_payment_hash_21, *payment_hash);
4367 assert_eq!(recv_value_21, amt);
4369 _ => panic!("Unexpected event"),
4372 Event::PaymentReceived { ref payment_hash, amt } => {
4373 assert_eq!(our_payment_hash_22, *payment_hash);
4374 assert_eq!(recv_value_22, amt);
4376 _ => panic!("Unexpected event"),
4379 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
4380 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
4381 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
4383 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat);
4384 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
4385 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
4386 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
4388 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
4389 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
4393 fn channel_monitor_network_test() {
4394 // Simple test which builds a network of ChannelManagers, connects them to each other, and
4395 // tests that ChannelMonitor is able to recover from various states.
4396 let nodes = create_network(5);
4398 // Create some initial channels
4399 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4400 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4401 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4402 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4404 // Rebalance the network a bit by relaying one payment through all the channels...
4405 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4406 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4407 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4408 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4410 // Simple case with no pending HTLCs:
4411 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
4413 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
4414 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4415 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4416 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
4418 get_announce_close_broadcast_events(&nodes, 0, 1);
4419 assert_eq!(nodes[0].node.list_channels().len(), 0);
4420 assert_eq!(nodes[1].node.list_channels().len(), 1);
4422 // One pending HTLC is discarded by the force-close:
4423 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
4425 // Simple case of one pending HTLC to HTLC-Timeout
4426 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
4428 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
4429 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4430 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4431 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
4433 get_announce_close_broadcast_events(&nodes, 1, 2);
4434 assert_eq!(nodes[1].node.list_channels().len(), 0);
4435 assert_eq!(nodes[2].node.list_channels().len(), 1);
4437 macro_rules! claim_funds {
4438 ($node: expr, $prev_node: expr, $preimage: expr) => {
4440 assert!($node.node.claim_funds($preimage));
4441 check_added_monitors!($node, 1);
4443 let events = $node.node.get_and_clear_pending_events();
4444 assert_eq!(events.len(), 1);
4446 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
4447 assert!(update_add_htlcs.is_empty());
4448 assert!(update_fail_htlcs.is_empty());
4449 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
4451 _ => panic!("Unexpected event"),
4457 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
4458 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
4459 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
4461 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
4463 // Claim the payment on nodes[3], giving it knowledge of the preimage
4464 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
4466 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4467 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
4469 check_preimage_claim(&nodes[3], &node_txn);
4471 get_announce_close_broadcast_events(&nodes, 2, 3);
4472 assert_eq!(nodes[2].node.list_channels().len(), 0);
4473 assert_eq!(nodes[3].node.list_channels().len(), 1);
4475 { // Cheat and reset nodes[4]'s height to 1
4476 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4477 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
4480 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
4481 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
4482 // One pending HTLC to time out:
4483 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
4484 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
4488 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4489 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4490 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
4491 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4492 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4495 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
4497 // Claim the payment on nodes[4], giving it knowledge of the preimage
4498 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
4500 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4501 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4502 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
4503 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4504 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4507 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
4509 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4510 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
4512 check_preimage_claim(&nodes[4], &node_txn);
4514 get_announce_close_broadcast_events(&nodes, 3, 4);
4515 assert_eq!(nodes[3].node.list_channels().len(), 0);
4516 assert_eq!(nodes[4].node.list_channels().len(), 0);
4518 // Create some new channels:
4519 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
4521 // A pending HTLC which will be revoked:
4522 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4523 // Get the will-be-revoked local txn from nodes[0]
4524 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
4525 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
4526 assert_eq!(revoked_local_txn[0].input.len(), 1);
4527 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
4528 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
4529 assert_eq!(revoked_local_txn[1].input.len(), 1);
4530 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4531 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4532 // Revoke the old state
4533 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
4536 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4537 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4539 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4540 assert_eq!(node_txn.len(), 3);
4541 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
4542 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
4544 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4545 node_txn.swap_remove(0);
4547 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
4549 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4550 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
4551 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4552 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
4553 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
4555 get_announce_close_broadcast_events(&nodes, 0, 1);
4556 assert_eq!(nodes[0].node.list_channels().len(), 0);
4557 assert_eq!(nodes[1].node.list_channels().len(), 0);
4561 fn revoked_output_claim() {
4562 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
4563 // transaction is broadcast by its counterparty
4564 let nodes = create_network(2);
4565 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4566 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
4567 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4568 assert_eq!(revoked_local_txn.len(), 1);
4569 // Only output is the full channel value back to nodes[0]:
4570 assert_eq!(revoked_local_txn[0].output.len(), 1);
4571 // Send a payment through, updating everyone's latest commitment txn
4572 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
4574 // Inform nodes[1] that nodes[0] broadcast a stale tx
4575 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4576 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4577 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4578 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
4580 assert_eq!(node_txn[0], node_txn[2]);
4582 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4583 check_spends!(node_txn[1], chan_1.3.clone());
4585 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
4586 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4587 get_announce_close_broadcast_events(&nodes, 0, 1);
4591 fn claim_htlc_outputs_shared_tx() {
4592 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
4593 let nodes = create_network(2);
4595 // Create some new channel:
4596 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4598 // Rebalance the network to generate htlc in the two directions
4599 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4600 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
4601 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4602 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4604 // Get the will-be-revoked local txn from node[0]
4605 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4606 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
4607 assert_eq!(revoked_local_txn[0].input.len(), 1);
4608 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4609 assert_eq!(revoked_local_txn[1].input.len(), 1);
4610 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4611 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4612 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
4614 //Revoke the old state
4615 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4618 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4620 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4622 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4623 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4624 assert_eq!(node_txn.len(), 4);
4626 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
4627 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4629 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
4631 let mut witness_lens = BTreeSet::new();
4632 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4633 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
4634 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
4635 assert_eq!(witness_lens.len(), 3);
4636 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4637 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4638 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4640 // Next nodes[1] broadcasts its current local tx state:
4641 assert_eq!(node_txn[1].input.len(), 1);
4642 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
4644 assert_eq!(node_txn[2].input.len(), 1);
4645 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
4646 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4647 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
4648 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4649 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
4651 get_announce_close_broadcast_events(&nodes, 0, 1);
4652 assert_eq!(nodes[0].node.list_channels().len(), 0);
4653 assert_eq!(nodes[1].node.list_channels().len(), 0);
4657 fn claim_htlc_outputs_single_tx() {
4658 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
4659 let nodes = create_network(2);
4661 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4663 // Rebalance the network to generate htlc in the two directions
4664 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4665 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
4666 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
4667 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4668 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4670 // Get the will-be-revoked local txn from node[0]
4671 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4673 //Revoke the old state
4674 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4677 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4679 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4681 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4682 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4683 assert_eq!(node_txn.len(), 12); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan)
4685 assert_eq!(node_txn[0], node_txn[7]);
4686 assert_eq!(node_txn[1], node_txn[8]);
4687 assert_eq!(node_txn[2], node_txn[9]);
4688 assert_eq!(node_txn[3], node_txn[10]);
4689 assert_eq!(node_txn[4], node_txn[11]);
4690 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
4691 assert_eq!(node_txn[4], node_txn[6]);
4693 assert_eq!(node_txn[0].input.len(), 1);
4694 assert_eq!(node_txn[1].input.len(), 1);
4695 assert_eq!(node_txn[2].input.len(), 1);
4697 let mut revoked_tx_map = HashMap::new();
4698 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
4699 node_txn[0].verify(&revoked_tx_map).unwrap();
4700 node_txn[1].verify(&revoked_tx_map).unwrap();
4701 node_txn[2].verify(&revoked_tx_map).unwrap();
4703 let mut witness_lens = BTreeSet::new();
4704 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4705 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
4706 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
4707 assert_eq!(witness_lens.len(), 3);
4708 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4709 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4710 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4712 assert_eq!(node_txn[3].input.len(), 1);
4713 check_spends!(node_txn[3], chan_1.3.clone());
4715 assert_eq!(node_txn[4].input.len(), 1);
4716 let witness_script = node_txn[4].input[0].witness.last().unwrap();
4717 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4718 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
4719 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4720 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
4722 get_announce_close_broadcast_events(&nodes, 0, 1);
4723 assert_eq!(nodes[0].node.list_channels().len(), 0);
4724 assert_eq!(nodes[1].node.list_channels().len(), 0);
4728 fn test_htlc_ignore_latest_remote_commitment() {
4729 // Test that HTLC transactions spending the latest remote commitment transaction are simply
4730 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
4731 let nodes = create_network(2);
4732 create_announced_chan_between_nodes(&nodes, 0, 1);
4734 route_payment(&nodes[0], &[&nodes[1]], 10000000);
4735 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
4737 let events = nodes[0].node.get_and_clear_pending_events();
4738 assert_eq!(events.len(), 1);
4740 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4741 assert_eq!(flags & 0b10, 0b10);
4743 _ => panic!("Unexpected event"),
4747 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4748 assert_eq!(node_txn.len(), 2);
4750 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4751 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4754 let events = nodes[1].node.get_and_clear_pending_events();
4755 assert_eq!(events.len(), 1);
4757 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4758 assert_eq!(flags & 0b10, 0b10);
4760 _ => panic!("Unexpected event"),
4764 // Duplicate the block_connected call since this may happen due to other listeners
4765 // registering new transactions
4766 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4770 fn test_force_close_fail_back() {
4771 // Check which HTLCs are failed-backwards on channel force-closure
4772 let mut nodes = create_network(3);
4773 create_announced_chan_between_nodes(&nodes, 0, 1);
4774 create_announced_chan_between_nodes(&nodes, 1, 2);
4776 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
4778 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4780 let mut payment_event = {
4781 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4782 check_added_monitors!(nodes[0], 1);
4784 let mut events = nodes[0].node.get_and_clear_pending_events();
4785 assert_eq!(events.len(), 1);
4786 SendEvent::from_event(events.remove(0))
4789 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4790 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4792 let events_1 = nodes[1].node.get_and_clear_pending_events();
4793 assert_eq!(events_1.len(), 1);
4795 Event::PendingHTLCsForwardable { .. } => { },
4796 _ => panic!("Unexpected event"),
4799 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
4800 nodes[1].node.process_pending_htlc_forwards();
4802 let mut events_2 = nodes[1].node.get_and_clear_pending_events();
4803 assert_eq!(events_2.len(), 1);
4804 payment_event = SendEvent::from_event(events_2.remove(0));
4805 assert_eq!(payment_event.msgs.len(), 1);
4807 check_added_monitors!(nodes[1], 1);
4808 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4809 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
4810 check_added_monitors!(nodes[2], 1);
4812 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
4813 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
4814 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
4816 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
4817 let events_3 = nodes[2].node.get_and_clear_pending_events();
4818 assert_eq!(events_3.len(), 1);
4820 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4821 assert_eq!(flags & 0b10, 0b10);
4823 _ => panic!("Unexpected event"),
4827 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4828 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
4829 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
4830 // back to nodes[1] upon timeout otherwise.
4831 assert_eq!(node_txn.len(), 1);
4835 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4836 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4838 let events_4 = nodes[1].node.get_and_clear_pending_events();
4839 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
4840 assert_eq!(events_4.len(), 1);
4842 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4843 assert_eq!(flags & 0b10, 0b10);
4845 _ => panic!("Unexpected event"),
4848 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
4850 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
4851 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
4852 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
4854 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4855 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4856 assert_eq!(node_txn.len(), 1);
4857 assert_eq!(node_txn[0].input.len(), 1);
4858 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
4859 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
4860 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
4862 check_spends!(node_txn[0], tx);
4866 fn test_unconf_chan() {
4867 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
4868 let nodes = create_network(2);
4869 create_announced_chan_between_nodes(&nodes, 0, 1);
4871 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4872 assert_eq!(channel_state.by_id.len(), 1);
4873 assert_eq!(channel_state.short_to_id.len(), 1);
4874 mem::drop(channel_state);
4876 let mut headers = Vec::new();
4877 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4878 headers.push(header.clone());
4880 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4881 headers.push(header.clone());
4883 while !headers.is_empty() {
4884 nodes[0].node.block_disconnected(&headers.pop().unwrap());
4887 let events = nodes[0].node.get_and_clear_pending_events();
4888 assert_eq!(events.len(), 1);
4890 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4891 assert_eq!(flags & 0b10, 0b10);
4893 _ => panic!("Unexpected event"),
4896 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4897 assert_eq!(channel_state.by_id.len(), 0);
4898 assert_eq!(channel_state.short_to_id.len(), 0);
4901 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
4902 /// for claims/fails they are separated out.
4903 fn reconnect_nodes(node_a: &Node, node_b: &Node, pre_all_htlcs: bool, pending_htlc_adds: (i64, i64), pending_htlc_claims: (usize, usize), pending_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool)) {
4904 let reestablish_1 = node_a.node.peer_connected(&node_b.node.get_our_node_id());
4905 let reestablish_2 = node_b.node.peer_connected(&node_a.node.get_our_node_id());
4907 let mut resp_1 = Vec::new();
4908 for msg in reestablish_1 {
4909 resp_1.push(node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap());
4911 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4912 check_added_monitors!(node_b, 1);
4914 check_added_monitors!(node_b, 0);
4917 let mut resp_2 = Vec::new();
4918 for msg in reestablish_2 {
4919 resp_2.push(node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap());
4921 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4922 check_added_monitors!(node_a, 1);
4924 check_added_monitors!(node_a, 0);
4927 // We dont yet support both needing updates, as that would require a different commitment dance:
4928 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
4929 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
4931 for chan_msgs in resp_1.drain(..) {
4933 let a = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
4934 let _announcement_sigs_opt = a.unwrap();
4935 //TODO: Test announcement_sigs re-sending when we've implemented it
4937 assert!(chan_msgs.0.is_none());
4940 assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4941 check_added_monitors!(node_a, 1);
4943 assert!(chan_msgs.1.is_none());
4945 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4946 let commitment_update = chan_msgs.2.unwrap();
4947 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4948 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
4950 assert!(commitment_update.update_add_htlcs.is_empty());
4952 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
4953 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
4954 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4955 for update_add in commitment_update.update_add_htlcs {
4956 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
4958 for update_fulfill in commitment_update.update_fulfill_htlcs {
4959 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
4961 for update_fail in commitment_update.update_fail_htlcs {
4962 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
4965 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4966 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
4968 let (as_revoke_and_ack, as_commitment_signed) = node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4969 check_added_monitors!(node_a, 1);
4970 assert!(as_commitment_signed.is_none());
4971 assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
4972 check_added_monitors!(node_b, 1);
4975 assert!(chan_msgs.2.is_none());
4979 for chan_msgs in resp_2.drain(..) {
4981 let _announcement_sigs_opt = node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
4982 //TODO: Test announcement_sigs re-sending when we've implemented it
4984 assert!(chan_msgs.0.is_none());
4987 assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4988 check_added_monitors!(node_b, 1);
4990 assert!(chan_msgs.1.is_none());
4992 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4993 let commitment_update = chan_msgs.2.unwrap();
4994 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
4995 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
4997 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
4998 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
4999 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
5000 for update_add in commitment_update.update_add_htlcs {
5001 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
5003 for update_fulfill in commitment_update.update_fulfill_htlcs {
5004 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
5006 for update_fail in commitment_update.update_fail_htlcs {
5007 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
5010 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
5011 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
5013 let (bs_revoke_and_ack, bs_commitment_signed) = node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
5014 check_added_monitors!(node_b, 1);
5015 assert!(bs_commitment_signed.is_none());
5016 assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5017 check_added_monitors!(node_a, 1);
5020 assert!(chan_msgs.2.is_none());
5026 fn test_simple_peer_disconnect() {
5027 // Test that we can reconnect when there are no lost messages
5028 let nodes = create_network(3);
5029 create_announced_chan_between_nodes(&nodes, 0, 1);
5030 create_announced_chan_between_nodes(&nodes, 1, 2);
5032 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5033 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5034 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5036 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5037 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5038 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
5039 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
5041 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5042 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5043 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5045 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5046 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5047 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5048 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5050 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5051 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5053 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
5054 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
5056 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
5058 let events = nodes[0].node.get_and_clear_pending_events();
5059 assert_eq!(events.len(), 2);
5061 Event::PaymentSent { payment_preimage } => {
5062 assert_eq!(payment_preimage, payment_preimage_3);
5064 _ => panic!("Unexpected event"),
5067 Event::PaymentFailed { payment_hash } => {
5068 assert_eq!(payment_hash, payment_hash_5);
5070 _ => panic!("Unexpected event"),
5074 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
5075 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
5078 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
5079 // Test that we can reconnect when in-flight HTLC updates get dropped
5080 let mut nodes = create_network(2);
5081 if messages_delivered == 0 {
5082 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
5083 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
5085 create_announced_chan_between_nodes(&nodes, 0, 1);
5088 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
5089 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
5091 let payment_event = {
5092 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
5093 check_added_monitors!(nodes[0], 1);
5095 let mut events = nodes[0].node.get_and_clear_pending_events();
5096 assert_eq!(events.len(), 1);
5097 SendEvent::from_event(events.remove(0))
5099 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
5101 if messages_delivered < 2 {
5102 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
5104 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5105 let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
5106 check_added_monitors!(nodes[1], 1);
5108 if messages_delivered >= 3 {
5109 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5110 check_added_monitors!(nodes[0], 1);
5112 if messages_delivered >= 4 {
5113 let (as_revoke_and_ack, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed.unwrap()).unwrap();
5114 assert!(as_commitment_signed.is_none());
5115 check_added_monitors!(nodes[0], 1);
5117 if messages_delivered >= 5 {
5118 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
5119 check_added_monitors!(nodes[1], 1);
5125 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5126 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5127 if messages_delivered < 2 {
5128 // Even if the funding_locked messages get exchanged, as long as nothing further was
5129 // received on either side, both sides will need to resend them.
5130 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
5131 } else if messages_delivered == 2 {
5132 // nodes[0] still wants its RAA + commitment_signed
5133 reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
5134 } else if messages_delivered == 3 {
5135 // nodes[0] still wants its commitment_signed
5136 reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
5137 } else if messages_delivered == 4 {
5138 // nodes[1] still wants its final RAA
5139 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
5140 } else if messages_delivered == 5 {
5141 // Everything was delivered...
5142 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5145 let events_1 = nodes[1].node.get_and_clear_pending_events();
5146 assert_eq!(events_1.len(), 1);
5148 Event::PendingHTLCsForwardable { .. } => { },
5149 _ => panic!("Unexpected event"),
5152 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5153 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5154 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5156 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
5157 nodes[1].node.process_pending_htlc_forwards();
5159 let events_2 = nodes[1].node.get_and_clear_pending_events();
5160 assert_eq!(events_2.len(), 1);
5162 Event::PaymentReceived { ref payment_hash, amt } => {
5163 assert_eq!(payment_hash_1, *payment_hash);
5164 assert_eq!(amt, 1000000);
5166 _ => panic!("Unexpected event"),
5169 nodes[1].node.claim_funds(payment_preimage_1);
5170 check_added_monitors!(nodes[1], 1);
5172 let events_3 = nodes[1].node.get_and_clear_pending_events();
5173 assert_eq!(events_3.len(), 1);
5174 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
5175 Event::UpdateHTLCs { ref node_id, ref updates } => {
5176 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5177 assert!(updates.update_add_htlcs.is_empty());
5178 assert!(updates.update_fail_htlcs.is_empty());
5179 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5180 assert!(updates.update_fail_malformed_htlcs.is_empty());
5181 assert!(updates.update_fee.is_none());
5182 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
5184 _ => panic!("Unexpected event"),
5187 if messages_delivered >= 1 {
5188 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
5190 let events_4 = nodes[0].node.get_and_clear_pending_events();
5191 assert_eq!(events_4.len(), 1);
5193 Event::PaymentSent { ref payment_preimage } => {
5194 assert_eq!(payment_preimage_1, *payment_preimage);
5196 _ => panic!("Unexpected event"),
5199 if messages_delivered >= 2 {
5200 let (as_revoke_and_ack, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
5201 check_added_monitors!(nodes[0], 1);
5203 if messages_delivered >= 3 {
5204 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
5205 check_added_monitors!(nodes[1], 1);
5207 if messages_delivered >= 4 {
5208 let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
5209 assert!(bs_commitment_signed.is_none());
5210 check_added_monitors!(nodes[1], 1);
5212 if messages_delivered >= 5 {
5213 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5214 check_added_monitors!(nodes[0], 1);
5221 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5222 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5223 if messages_delivered < 2 {
5224 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
5225 //TODO: Deduplicate PaymentSent events, then enable this if:
5226 //if messages_delivered < 1 {
5227 let events_4 = nodes[0].node.get_and_clear_pending_events();
5228 assert_eq!(events_4.len(), 1);
5230 Event::PaymentSent { ref payment_preimage } => {
5231 assert_eq!(payment_preimage_1, *payment_preimage);
5233 _ => panic!("Unexpected event"),
5236 } else if messages_delivered == 2 {
5237 // nodes[0] still wants its RAA + commitment_signed
5238 reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
5239 } else if messages_delivered == 3 {
5240 // nodes[0] still wants its commitment_signed
5241 reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
5242 } else if messages_delivered == 4 {
5243 // nodes[1] still wants its final RAA
5244 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
5245 } else if messages_delivered == 5 {
5246 // Everything was delivered...
5247 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5250 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5251 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5252 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5254 // Channel should still work fine...
5255 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
5256 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
5260 fn test_drop_messages_peer_disconnect_a() {
5261 do_test_drop_messages_peer_disconnect(0);
5262 do_test_drop_messages_peer_disconnect(1);
5263 do_test_drop_messages_peer_disconnect(2);
5267 fn test_drop_messages_peer_disconnect_b() {
5268 do_test_drop_messages_peer_disconnect(3);
5269 do_test_drop_messages_peer_disconnect(4);
5270 do_test_drop_messages_peer_disconnect(5);
5274 fn test_funding_peer_disconnect() {
5275 // Test that we can lock in our funding tx while disconnected
5276 let nodes = create_network(2);
5277 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
5279 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5280 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5282 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
5283 let events_1 = nodes[0].node.get_and_clear_pending_events();
5284 assert_eq!(events_1.len(), 1);
5286 Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5287 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5288 assert!(announcement_sigs.is_none());
5290 _ => panic!("Unexpected event"),
5293 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
5294 let events_2 = nodes[1].node.get_and_clear_pending_events();
5295 assert_eq!(events_2.len(), 1);
5297 Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5298 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5299 assert!(announcement_sigs.is_none());
5301 _ => panic!("Unexpected event"),
5304 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5305 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5306 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5307 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5309 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
5310 // rebroadcasting announcement_signatures upon reconnect.
5312 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
5313 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
5314 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
5318 fn test_invalid_channel_announcement() {
5319 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
5320 let secp_ctx = Secp256k1::new();
5321 let nodes = create_network(2);
5323 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
5325 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
5326 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
5327 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5328 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5330 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
5332 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
5333 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
5335 let as_network_key = nodes[0].node.get_our_node_id();
5336 let bs_network_key = nodes[1].node.get_our_node_id();
5338 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
5340 let mut chan_announcement;
5342 macro_rules! dummy_unsigned_msg {
5344 msgs::UnsignedChannelAnnouncement {
5345 features: msgs::GlobalFeatures::new(),
5346 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
5347 short_channel_id: as_chan.get_short_channel_id().unwrap(),
5348 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
5349 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
5350 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
5351 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
5352 excess_data: Vec::new(),
5357 macro_rules! sign_msg {
5358 ($unsigned_msg: expr) => {
5359 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
5360 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
5361 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
5362 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
5363 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
5364 chan_announcement = msgs::ChannelAnnouncement {
5365 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
5366 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
5367 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
5368 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
5369 contents: $unsigned_msg
5374 let unsigned_msg = dummy_unsigned_msg!();
5375 sign_msg!(unsigned_msg);
5376 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
5377 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
5379 // Configured with Network::Testnet
5380 let mut unsigned_msg = dummy_unsigned_msg!();
5381 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
5382 sign_msg!(unsigned_msg);
5383 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
5385 let mut unsigned_msg = dummy_unsigned_msg!();
5386 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
5387 sign_msg!(unsigned_msg);
5388 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());