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::{ChannelMessageHandler, HandleError, RAACommitmentOrder};
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);
1384 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1385 let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1386 let mut pending_events = self.pending_events.lock().unwrap();
1387 if let Some(channel_update) = channel_update {
1388 pending_events.push(events::Event::PaymentFailureNetworkUpdate {
1389 update: channel_update,
1392 pending_events.push(events::Event::PaymentFailed {
1393 payment_hash: payment_hash.clone(),
1394 rejected_by_dest: !payment_retryable,
1397 panic!("should have onion error packet here");
1400 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1401 let err_packet = match onion_error {
1402 HTLCFailReason::Reason { failure_code, data } => {
1403 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1404 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1406 HTLCFailReason::ErrorPacket { err } => {
1407 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1411 let (node_id, fail_msgs) = {
1412 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1413 Some(chan_id) => chan_id.clone(),
1417 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1418 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1419 Ok(msg) => (chan.get_their_node_id(), msg),
1421 //TODO: Do something with e?
1428 Some((msg, commitment_msg, chan_monitor)) => {
1429 mem::drop(channel_state);
1431 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1432 unimplemented!();// but def dont push the event...
1435 let mut pending_events = self.pending_events.lock().unwrap();
1436 pending_events.push(events::Event::UpdateHTLCs {
1438 updates: msgs::CommitmentUpdate {
1439 update_add_htlcs: Vec::new(),
1440 update_fulfill_htlcs: Vec::new(),
1441 update_fail_htlcs: vec![msg],
1442 update_fail_malformed_htlcs: Vec::new(),
1444 commitment_signed: commitment_msg,
1454 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1455 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1456 /// should probably kick the net layer to go send messages if this returns true!
1458 /// May panic if called except in response to a PaymentReceived event.
1459 pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1460 let mut sha = Sha256::new();
1461 sha.input(&payment_preimage);
1462 let mut payment_hash = [0; 32];
1463 sha.result(&mut payment_hash);
1465 let mut channel_state = Some(self.channel_state.lock().unwrap());
1466 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1467 if let Some(mut sources) = removed_source {
1468 for htlc_with_hash in sources.drain(..) {
1469 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1470 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1475 fn claim_funds_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1477 HTLCSource::OutboundRoute { .. } => {
1478 mem::drop(channel_state);
1479 let mut pending_events = self.pending_events.lock().unwrap();
1480 pending_events.push(events::Event::PaymentSent {
1484 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1485 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1486 let (node_id, fulfill_msgs) = {
1487 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1488 Some(chan_id) => chan_id.clone(),
1490 // TODO: There is probably a channel manager somewhere that needs to
1491 // learn the preimage as the channel already hit the chain and that's
1497 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1498 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1499 Ok(msg) => (chan.get_their_node_id(), msg),
1501 // TODO: There is probably a channel manager somewhere that needs to
1502 // learn the preimage as the channel may be about to hit the chain.
1503 //TODO: Do something with e?
1509 mem::drop(channel_state);
1510 if let Some(chan_monitor) = fulfill_msgs.1 {
1511 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1512 unimplemented!();// but def dont push the event...
1516 if let Some((msg, commitment_msg)) = fulfill_msgs.0 {
1517 let mut pending_events = self.pending_events.lock().unwrap();
1518 pending_events.push(events::Event::UpdateHTLCs {
1520 updates: msgs::CommitmentUpdate {
1521 update_add_htlcs: Vec::new(),
1522 update_fulfill_htlcs: vec![msg],
1523 update_fail_htlcs: Vec::new(),
1524 update_fail_malformed_htlcs: Vec::new(),
1526 commitment_signed: commitment_msg,
1534 /// Gets the node_id held by this ChannelManager
1535 pub fn get_our_node_id(&self) -> PublicKey {
1536 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1539 /// Used to restore channels to normal operation after a
1540 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1542 pub fn test_restore_channel_monitor(&self) {
1546 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, MsgHandleErrInternal> {
1547 if msg.chain_hash != self.genesis_hash {
1548 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1550 let mut channel_state = self.channel_state.lock().unwrap();
1551 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
1552 return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone()));
1555 let chan_keys = if cfg!(feature = "fuzztarget") {
1557 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(),
1558 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(),
1559 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(),
1560 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(),
1561 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(),
1562 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(),
1563 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(),
1564 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],
1567 let mut key_seed = [0u8; 32];
1568 rng::fill_bytes(&mut key_seed);
1569 match ChannelKeys::new_from_seed(&key_seed) {
1571 Err(_) => panic!("RNG is busted!")
1575 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))
1576 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1577 let accept_msg = channel.get_accept_channel();
1578 channel_state.by_id.insert(channel.channel_id(), channel);
1582 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1583 let (value, output_script, user_id) = {
1584 let mut channel_state = self.channel_state.lock().unwrap();
1585 match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
1587 if chan.get_their_node_id() != *their_node_id {
1588 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1589 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1591 chan.accept_channel(&msg)
1592 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.temporary_channel_id))?;
1593 (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
1595 //TODO: same as above
1596 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1599 let mut pending_events = self.pending_events.lock().unwrap();
1600 pending_events.push(events::Event::FundingGenerationReady {
1601 temporary_channel_id: msg.temporary_channel_id,
1602 channel_value_satoshis: value,
1603 output_script: output_script,
1604 user_channel_id: user_id,
1609 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, MsgHandleErrInternal> {
1610 let (chan, funding_msg, monitor_update) = {
1611 let mut channel_state = self.channel_state.lock().unwrap();
1612 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1613 hash_map::Entry::Occupied(mut chan) => {
1614 if chan.get().get_their_node_id() != *their_node_id {
1615 //TODO: here and below MsgHandleErrInternal, #153 case
1616 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1618 match chan.get_mut().funding_created(msg) {
1619 Ok((funding_msg, monitor_update)) => {
1620 (chan.remove(), funding_msg, monitor_update)
1623 return Err(e).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1627 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1629 }; // Release channel lock for install_watch_outpoint call,
1630 // note that this means if the remote end is misbehaving and sends a message for the same
1631 // channel back-to-back with funding_created, we'll end up thinking they sent a message
1632 // for a bogus channel.
1633 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1636 let mut channel_state = self.channel_state.lock().unwrap();
1637 match channel_state.by_id.entry(funding_msg.channel_id) {
1638 hash_map::Entry::Occupied(_) => {
1639 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1641 hash_map::Entry::Vacant(e) => {
1648 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1649 let (funding_txo, user_id, monitor) = {
1650 let mut channel_state = self.channel_state.lock().unwrap();
1651 match channel_state.by_id.get_mut(&msg.channel_id) {
1653 if chan.get_their_node_id() != *their_node_id {
1654 //TODO: here and below MsgHandleErrInternal, #153 case
1655 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1657 let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1658 (chan.get_funding_txo().unwrap(), chan.get_user_id(), chan_monitor)
1660 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1663 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1666 let mut pending_events = self.pending_events.lock().unwrap();
1667 pending_events.push(events::Event::FundingBroadcastSafe {
1668 funding_txo: funding_txo,
1669 user_channel_id: user_id,
1674 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, MsgHandleErrInternal> {
1675 let mut channel_state = self.channel_state.lock().unwrap();
1676 match channel_state.by_id.get_mut(&msg.channel_id) {
1678 if chan.get_their_node_id() != *their_node_id {
1679 //TODO: here and below MsgHandleErrInternal, #153 case
1680 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1682 chan.funding_locked(&msg)
1683 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
1684 return Ok(self.get_announcement_sigs(chan));
1686 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1690 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), MsgHandleErrInternal> {
1691 let (mut res, chan_option) = {
1692 let mut channel_state_lock = self.channel_state.lock().unwrap();
1693 let channel_state = channel_state_lock.borrow_parts();
1695 match channel_state.by_id.entry(msg.channel_id.clone()) {
1696 hash_map::Entry::Occupied(mut chan_entry) => {
1697 if chan_entry.get().get_their_node_id() != *their_node_id {
1698 //TODO: here and below MsgHandleErrInternal, #153 case
1699 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1701 let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1702 if chan_entry.get().is_shutdown() {
1703 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1704 channel_state.short_to_id.remove(&short_id);
1706 (res, Some(chan_entry.remove_entry().1))
1707 } else { (res, None) }
1709 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1712 for htlc_source in res.2.drain(..) {
1713 // unknown_next_peer...I dunno who that is anymore....
1714 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() });
1716 if let Some(chan) = chan_option {
1717 if let Ok(update) = self.get_channel_update(&chan) {
1718 let mut events = self.pending_events.lock().unwrap();
1719 events.push(events::Event::BroadcastChannelUpdate {
1727 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, MsgHandleErrInternal> {
1728 let (res, chan_option) = {
1729 let mut channel_state_lock = self.channel_state.lock().unwrap();
1730 let channel_state = channel_state_lock.borrow_parts();
1731 match channel_state.by_id.entry(msg.channel_id.clone()) {
1732 hash_map::Entry::Occupied(mut chan_entry) => {
1733 if chan_entry.get().get_their_node_id() != *their_node_id {
1734 //TODO: here and below MsgHandleErrInternal, #153 case
1735 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1737 let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1738 if res.1.is_some() {
1739 // We're done with this channel, we've got a signed closing transaction and
1740 // will send the closing_signed back to the remote peer upon return. This
1741 // also implies there are no pending HTLCs left on the channel, so we can
1742 // fully delete it from tracking (the channel monitor is still around to
1743 // watch for old state broadcasts)!
1744 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1745 channel_state.short_to_id.remove(&short_id);
1747 (res, Some(chan_entry.remove_entry().1))
1748 } else { (res, None) }
1750 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1753 if let Some(broadcast_tx) = res.1 {
1754 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1756 if let Some(chan) = chan_option {
1757 if let Ok(update) = self.get_channel_update(&chan) {
1758 let mut events = self.pending_events.lock().unwrap();
1759 events.push(events::Event::BroadcastChannelUpdate {
1767 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1768 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1769 //determine the state of the payment based on our response/if we forward anything/the time
1770 //we take to respond. We should take care to avoid allowing such an attack.
1772 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1773 //us repeatedly garbled in different ways, and compare our error messages, which are
1774 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1775 //but we should prevent it anyway.
1777 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1778 let channel_state = channel_state_lock.borrow_parts();
1780 match channel_state.by_id.get_mut(&msg.channel_id) {
1782 if chan.get_their_node_id() != *their_node_id {
1783 //TODO: here MsgHandleErrInternal, #153 case
1784 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1786 if !chan.is_usable() {
1787 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Channel not yet available for receiving HTLCs", action: Some(msgs::ErrorAction::IgnoreError)}));
1789 chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1791 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1795 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1796 let mut channel_state = self.channel_state.lock().unwrap();
1797 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
1799 if chan.get_their_node_id() != *their_node_id {
1800 //TODO: here and below MsgHandleErrInternal, #153 case
1801 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1803 chan.update_fulfill_htlc(&msg)
1804 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?.clone()
1806 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1808 self.claim_funds_internal(channel_state, htlc_source, msg.payment_preimage.clone());
1812 // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
1813 // indicating that the payment itself failed
1814 fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
1815 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
1816 macro_rules! onion_failure_log {
1817 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
1818 log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
1820 ( $error_code_textual: expr, $error_code: expr ) => {
1821 log_trace!(self, "{}({})", $error_code_textual, $error_code);
1825 const BADONION: u16 = 0x8000;
1826 const PERM: u16 = 0x4000;
1827 const UPDATE: u16 = 0x1000;
1830 let mut htlc_msat = *first_hop_htlc_msat;
1832 // Handle packed channel/node updates for passing back for the route handler
1833 Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
1834 if res.is_some() { return; }
1836 let incoming_htlc_msat = htlc_msat;
1837 let amt_to_forward = htlc_msat - route_hop.fee_msat;
1838 htlc_msat = amt_to_forward;
1840 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
1842 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1843 decryption_tmp.resize(packet_decrypted.len(), 0);
1844 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1845 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1846 packet_decrypted = decryption_tmp;
1848 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
1850 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
1851 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
1852 let mut hmac = Hmac::new(Sha256::new(), &um);
1853 hmac.input(&err_packet.encode()[32..]);
1854 let mut calc_tag = [0u8; 32];
1855 hmac.raw_result(&mut calc_tag);
1857 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
1858 if err_packet.failuremsg.len() < 2 {
1859 // Useless packet that we can't use but it passed HMAC, so it
1860 // definitely came from the peer in question
1861 res = Some((None, !is_from_final_node));
1863 let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
1865 match error_code & 0xff {
1867 // either from an intermediate or final node
1868 // invalid_realm(PERM|1),
1869 // temporary_node_failure(NODE|2)
1870 // permanent_node_failure(PERM|NODE|2)
1871 // required_node_feature_mssing(PERM|NODE|3)
1872 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1873 node_id: route_hop.pubkey,
1874 is_permanent: error_code & PERM == PERM,
1875 }), !(error_code & PERM == PERM && is_from_final_node)));
1876 // node returning invalid_realm is removed from network_map,
1877 // although NODE flag is not set, TODO: or remove channel only?
1878 // retry payment when removed node is not a final node
1884 if is_from_final_node {
1885 let payment_retryable = match error_code {
1886 c if c == PERM|15 => false, // unknown_payment_hash
1887 c if c == PERM|16 => false, // incorrect_payment_amount
1888 17 => true, // final_expiry_too_soon
1889 18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
1890 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
1893 19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
1894 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1898 // A final node has sent us either an invalid code or an error_code that
1899 // MUST be sent from the processing node, or the formmat of failuremsg
1900 // does not coform to the spec.
1901 // Remove it from the network map and don't may retry payment
1902 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1903 node_id: route_hop.pubkey,
1909 res = Some((None, payment_retryable));
1913 // now, error_code should be only from the intermediate nodes
1915 _c if error_code & PERM == PERM => {
1916 res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1917 short_channel_id: route_hop.short_channel_id,
1921 _c if error_code & UPDATE == UPDATE => {
1922 let offset = match error_code {
1923 c if c == UPDATE|7 => 0, // temporary_channel_failure
1924 c if c == UPDATE|11 => 8, // amount_below_minimum
1925 c if c == UPDATE|12 => 8, // fee_insufficient
1926 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
1927 c if c == UPDATE|14 => 0, // expiry_too_soon
1928 c if c == UPDATE|20 => 2, // channel_disabled
1930 // node sending unknown code
1931 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1932 node_id: route_hop.pubkey,
1939 if err_packet.failuremsg.len() >= offset + 2 {
1940 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
1941 if err_packet.failuremsg.len() >= offset + 4 + update_len {
1942 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
1943 // if channel_update should NOT have caused the failure:
1944 // MAY treat the channel_update as invalid.
1945 let is_chan_update_invalid = match error_code {
1946 c if c == UPDATE|7 => { // temporary_channel_failure
1949 c if c == UPDATE|11 => { // amount_below_minimum
1950 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1951 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
1952 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
1954 c if c == UPDATE|12 => { // fee_insufficient
1955 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
1956 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) });
1957 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
1958 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
1960 c if c == UPDATE|13 => { // incorrect_cltv_expiry
1961 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
1962 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
1963 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
1965 c if c == UPDATE|20 => { // channel_disabled
1966 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
1967 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
1968 chan_update.contents.flags & 0x01 == 0x01
1970 c if c == UPDATE|21 => true, // expiry_too_far
1971 _ => { unreachable!(); },
1974 let msg = if is_chan_update_invalid { None } else {
1975 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1979 res = Some((msg, true));
1985 _c if error_code & BADONION == BADONION => {
1988 14 => { // expiry_too_soon
1989 res = Some((None, true));
1993 // node sending unknown code
1994 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1995 node_id: route_hop.pubkey,
2004 }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2005 res.unwrap_or((None, true))
2006 } else { ((None, true)) }
2009 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2010 let mut channel_state = self.channel_state.lock().unwrap();
2011 match channel_state.by_id.get_mut(&msg.channel_id) {
2013 if chan.get_their_node_id() != *their_node_id {
2014 //TODO: here and below MsgHandleErrInternal, #153 case
2015 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2017 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() })
2018 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
2020 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
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>, RAACommitmentOrder), 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, order) = 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, order)), 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<(), 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>, RAACommitmentOrder), 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, rejected_by_dest } => {
3300 assert_eq!(payment_hash, our_payment_hash);
3301 assert!(rejected_by_dest);
3303 _ => panic!("Unexpected event"),
3308 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
3309 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
3312 fn create_network(node_count: usize) -> Vec<Node> {
3313 let mut nodes = Vec::new();
3314 let mut rng = thread_rng();
3315 let secp_ctx = Secp256k1::new();
3316 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
3318 let chan_count = Rc::new(RefCell::new(0));
3319 let payment_count = Rc::new(RefCell::new(0));
3321 for _ in 0..node_count {
3322 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
3323 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
3324 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
3325 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
3327 let mut key_slice = [0; 32];
3328 rng.fill_bytes(&mut key_slice);
3329 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
3331 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();
3332 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
3333 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router,
3334 network_payment_count: payment_count.clone(),
3335 network_chan_count: chan_count.clone(),
3343 fn test_async_inbound_update_fee() {
3344 let mut nodes = create_network(2);
3345 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3346 let channel_id = chan.2;
3348 macro_rules! get_feerate {
3350 let chan_lock = $node.node.channel_state.lock().unwrap();
3351 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3357 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3361 // send (1) commitment_signed -.
3362 // <- update_add_htlc/commitment_signed
3363 // send (2) RAA (awaiting remote revoke) -.
3364 // (1) commitment_signed is delivered ->
3365 // .- send (3) RAA (awaiting remote revoke)
3366 // (2) RAA is delivered ->
3367 // .- send (4) commitment_signed
3368 // <- (3) RAA is delivered
3369 // send (5) commitment_signed -.
3370 // <- (4) commitment_signed is delivered
3372 // (5) commitment_signed is delivered ->
3374 // (6) RAA is delivered ->
3376 // First nodes[0] generates an update_fee
3377 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3378 check_added_monitors!(nodes[0], 1);
3380 let events_0 = nodes[0].node.get_and_clear_pending_events();
3381 assert_eq!(events_0.len(), 1);
3382 let (update_msg, commitment_signed) = match events_0[0] { // (1)
3383 Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3384 (update_fee.as_ref(), commitment_signed)
3386 _ => panic!("Unexpected event"),
3389 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3391 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3392 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3393 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();
3394 check_added_monitors!(nodes[1], 1);
3396 let payment_event = {
3397 let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3398 assert_eq!(events_1.len(), 1);
3399 SendEvent::from_event(events_1.remove(0))
3401 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3402 assert_eq!(payment_event.msgs.len(), 1);
3404 // ...now when the messages get delivered everyone should be happy
3405 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3406 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)
3407 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3408 check_added_monitors!(nodes[0], 1);
3410 // deliver(1), generate (3):
3411 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3412 assert!(bs_commitment_signed.is_none()); // nodes[1] is awaiting nodes[0] revoke_and_ack
3413 check_added_monitors!(nodes[1], 1);
3415 let bs_update = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
3416 assert!(bs_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (4)
3417 assert!(bs_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (4)
3418 assert!(bs_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (4)
3419 assert!(bs_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (4)
3420 assert!(bs_update.as_ref().unwrap().update_fee.is_none()); // (4)
3421 check_added_monitors!(nodes[1], 1);
3423 let as_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap(); // deliver (3)
3424 assert!(as_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (5)
3425 assert!(as_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (5)
3426 assert!(as_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (5)
3427 assert!(as_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (5)
3428 assert!(as_update.as_ref().unwrap().update_fee.is_none()); // (5)
3429 check_added_monitors!(nodes[0], 1);
3431 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)
3432 assert!(as_second_commitment_signed.is_none()); // only (6)
3433 check_added_monitors!(nodes[0], 1);
3435 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)
3436 assert!(bs_second_commitment_signed.is_none());
3437 check_added_monitors!(nodes[1], 1);
3439 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3440 check_added_monitors!(nodes[0], 1);
3442 let events_2 = nodes[0].node.get_and_clear_pending_events();
3443 assert_eq!(events_2.len(), 1);
3445 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
3446 _ => panic!("Unexpected event"),
3449 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none()); // deliver (6)
3450 check_added_monitors!(nodes[1], 1);
3454 fn test_update_fee_unordered_raa() {
3455 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
3456 // crash in an earlier version of the update_fee patch)
3457 let mut nodes = create_network(2);
3458 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3459 let channel_id = chan.2;
3461 macro_rules! get_feerate {
3463 let chan_lock = $node.node.channel_state.lock().unwrap();
3464 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3470 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3472 // First nodes[0] generates an update_fee
3473 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3474 check_added_monitors!(nodes[0], 1);
3476 let events_0 = nodes[0].node.get_and_clear_pending_events();
3477 assert_eq!(events_0.len(), 1);
3478 let update_msg = match events_0[0] { // (1)
3479 Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
3482 _ => panic!("Unexpected event"),
3485 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3487 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3488 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3489 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();
3490 check_added_monitors!(nodes[1], 1);
3492 let payment_event = {
3493 let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3494 assert_eq!(events_1.len(), 1);
3495 SendEvent::from_event(events_1.remove(0))
3497 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3498 assert_eq!(payment_event.msgs.len(), 1);
3500 // ...now when the messages get delivered everyone should be happy
3501 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3502 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)
3503 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3504 check_added_monitors!(nodes[0], 1);
3506 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none()); // deliver (2)
3507 check_added_monitors!(nodes[1], 1);
3509 // We can't continue, sadly, because our (1) now has a bogus signature
3513 fn test_multi_flight_update_fee() {
3514 let nodes = create_network(2);
3515 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3516 let channel_id = chan.2;
3518 macro_rules! get_feerate {
3520 let chan_lock = $node.node.channel_state.lock().unwrap();
3521 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3527 // update_fee/commitment_signed ->
3528 // .- send (1) RAA and (2) commitment_signed
3529 // update_fee (never committed) ->
3530 // (3) update_fee ->
3531 // We have to manually generate the above update_fee, it is allowed by the protocol but we
3532 // don't track which updates correspond to which revoke_and_ack responses so we're in
3533 // AwaitingRAA mode and will not generate the update_fee yet.
3534 // <- (1) RAA delivered
3535 // (3) is generated and send (4) CS -.
3536 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
3537 // know the per_commitment_point to use for it.
3538 // <- (2) commitment_signed delivered
3539 // revoke_and_ack ->
3540 // B should send no response here
3541 // (4) commitment_signed delivered ->
3542 // <- RAA/commitment_signed delivered
3543 // revoke_and_ack ->
3545 // First nodes[0] generates an update_fee
3546 let initial_feerate = get_feerate!(nodes[0]);
3547 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
3548 check_added_monitors!(nodes[0], 1);
3550 let events_0 = nodes[0].node.get_and_clear_pending_events();
3551 assert_eq!(events_0.len(), 1);
3552 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
3553 Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3554 (update_fee.as_ref().unwrap(), commitment_signed)
3556 _ => panic!("Unexpected event"),
3559 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
3560 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
3561 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
3562 check_added_monitors!(nodes[1], 1);
3564 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
3566 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
3567 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3569 // Create the (3) update_fee message that nodes[0] will generate before it does...
3570 let mut update_msg_2 = msgs::UpdateFee {
3571 channel_id: update_msg_1.channel_id.clone(),
3572 feerate_per_kw: (initial_feerate + 30) as u32,
3575 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3577 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
3579 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3581 // Deliver (1), generating (3) and (4)
3582 let as_second_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
3583 check_added_monitors!(nodes[0], 1);
3584 assert!(as_second_update.as_ref().unwrap().update_add_htlcs.is_empty());
3585 assert!(as_second_update.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3586 assert!(as_second_update.as_ref().unwrap().update_fail_htlcs.is_empty());
3587 assert!(as_second_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3588 // Check that the update_fee newly generated matches what we delivered:
3589 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
3590 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
3592 // Deliver (2) commitment_signed
3593 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();
3594 check_added_monitors!(nodes[0], 1);
3595 assert!(as_commitment_signed.is_none());
3597 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none());
3598 check_added_monitors!(nodes[1], 1);
3601 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();
3602 check_added_monitors!(nodes[1], 1);
3604 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3605 check_added_monitors!(nodes[0], 1);
3607 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();
3608 assert!(as_second_commitment.is_none());
3609 check_added_monitors!(nodes[0], 1);
3611 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none());
3612 check_added_monitors!(nodes[1], 1);
3616 fn test_update_fee_vanilla() {
3617 let nodes = create_network(2);
3618 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3619 let channel_id = chan.2;
3621 macro_rules! get_feerate {
3623 let chan_lock = $node.node.channel_state.lock().unwrap();
3624 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3629 let feerate = get_feerate!(nodes[0]);
3630 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3632 let events_0 = nodes[0].node.get_and_clear_pending_events();
3633 assert_eq!(events_0.len(), 1);
3634 let (update_msg, commitment_signed) = match events_0[0] {
3635 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 } } => {
3636 (update_fee.as_ref(), commitment_signed)
3638 _ => panic!("Unexpected event"),
3640 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3642 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3643 let commitment_signed = commitment_signed.unwrap();
3644 check_added_monitors!(nodes[0], 1);
3645 check_added_monitors!(nodes[1], 1);
3647 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3648 assert!(resp_option.is_none());
3649 check_added_monitors!(nodes[0], 1);
3651 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3652 assert!(commitment_signed.is_none());
3653 check_added_monitors!(nodes[0], 1);
3655 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3656 assert!(resp_option.is_none());
3657 check_added_monitors!(nodes[1], 1);
3661 fn test_update_fee_with_fundee_update_add_htlc() {
3662 let mut nodes = create_network(2);
3663 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3664 let channel_id = chan.2;
3666 macro_rules! get_feerate {
3668 let chan_lock = $node.node.channel_state.lock().unwrap();
3669 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3675 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3677 let feerate = get_feerate!(nodes[0]);
3678 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3680 let events_0 = nodes[0].node.get_and_clear_pending_events();
3681 assert_eq!(events_0.len(), 1);
3682 let (update_msg, commitment_signed) = match events_0[0] {
3683 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 } } => {
3684 (update_fee.as_ref(), commitment_signed)
3686 _ => panic!("Unexpected event"),
3688 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3689 check_added_monitors!(nodes[0], 1);
3690 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3691 let commitment_signed = commitment_signed.unwrap();
3692 check_added_monitors!(nodes[1], 1);
3694 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
3696 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
3698 // nothing happens since node[1] is in AwaitingRemoteRevoke
3699 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
3701 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
3702 assert_eq!(added_monitors.len(), 0);
3703 added_monitors.clear();
3705 let events = nodes[0].node.get_and_clear_pending_events();
3706 assert_eq!(events.len(), 0);
3707 // node[1] has nothing to do
3709 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3710 assert!(resp_option.is_none());
3711 check_added_monitors!(nodes[0], 1);
3713 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3714 assert!(commitment_signed.is_none());
3715 check_added_monitors!(nodes[0], 1);
3716 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3717 // AwaitingRemoteRevoke ends here
3719 let commitment_update = resp_option.unwrap();
3720 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
3721 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
3722 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
3723 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
3724 assert_eq!(commitment_update.update_fee.is_none(), true);
3726 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
3727 let (revoke, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3728 check_added_monitors!(nodes[0], 1);
3729 check_added_monitors!(nodes[1], 1);
3730 let commitment_signed = commitment_signed.unwrap();
3731 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
3732 check_added_monitors!(nodes[1], 1);
3733 assert!(resp_option.is_none());
3735 let (revoke, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
3736 check_added_monitors!(nodes[1], 1);
3737 assert!(commitment_signed.is_none());
3738 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
3739 check_added_monitors!(nodes[0], 1);
3740 assert!(resp_option.is_none());
3742 let events = nodes[0].node.get_and_clear_pending_events();
3743 assert_eq!(events.len(), 1);
3745 Event::PendingHTLCsForwardable { .. } => { },
3746 _ => panic!("Unexpected event"),
3748 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
3749 nodes[0].node.process_pending_htlc_forwards();
3751 let events = nodes[0].node.get_and_clear_pending_events();
3752 assert_eq!(events.len(), 1);
3754 Event::PaymentReceived { .. } => { },
3755 _ => panic!("Unexpected event"),
3758 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
3760 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
3761 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
3762 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3766 fn test_update_fee() {
3767 let nodes = create_network(2);
3768 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3769 let channel_id = chan.2;
3771 macro_rules! get_feerate {
3773 let chan_lock = $node.node.channel_state.lock().unwrap();
3774 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3780 // (1) update_fee/commitment_signed ->
3781 // <- (2) revoke_and_ack
3782 // .- send (3) commitment_signed
3783 // (4) update_fee/commitment_signed ->
3784 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
3785 // <- (3) commitment_signed delivered
3786 // send (6) revoke_and_ack -.
3787 // <- (5) deliver revoke_and_ack
3788 // (6) deliver revoke_and_ack ->
3789 // .- send (7) commitment_signed in response to (4)
3790 // <- (7) deliver commitment_signed
3791 // revoke_and_ack ->
3793 // Create and deliver (1)...
3794 let feerate = get_feerate!(nodes[0]);
3795 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3797 let events_0 = nodes[0].node.get_and_clear_pending_events();
3798 assert_eq!(events_0.len(), 1);
3799 let (update_msg, commitment_signed) = match events_0[0] {
3800 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 } } => {
3801 (update_fee.as_ref(), commitment_signed)
3803 _ => panic!("Unexpected event"),
3805 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3807 // Generate (2) and (3):
3808 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3809 let commitment_signed_0 = commitment_signed.unwrap();
3810 check_added_monitors!(nodes[0], 1);
3811 check_added_monitors!(nodes[1], 1);
3814 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3815 assert!(resp_option.is_none());
3816 check_added_monitors!(nodes[0], 1);
3818 // Create and deliver (4)...
3819 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
3820 let events_0 = nodes[0].node.get_and_clear_pending_events();
3821 assert_eq!(events_0.len(), 1);
3822 let (update_msg, commitment_signed) = match events_0[0] {
3823 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 } } => {
3824 (update_fee.as_ref(), commitment_signed)
3826 _ => panic!("Unexpected event"),
3828 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3830 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3832 assert!(commitment_signed.is_none());
3833 check_added_monitors!(nodes[0], 1);
3834 check_added_monitors!(nodes[1], 1);
3836 // Handle (3), creating (6):
3837 let (revoke_msg_0, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
3838 assert!(commitment_signed.is_none());
3839 check_added_monitors!(nodes[0], 1);
3842 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3843 assert!(resp_option.is_none());
3844 check_added_monitors!(nodes[0], 1);
3846 // Deliver (6), creating (7):
3847 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
3848 let commitment_signed = resp_option.unwrap().commitment_signed;
3849 check_added_monitors!(nodes[1], 1);
3852 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3853 assert!(commitment_signed.is_none());
3854 check_added_monitors!(nodes[0], 1);
3855 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3856 assert!(resp_option.is_none());
3857 check_added_monitors!(nodes[1], 1);
3859 assert_eq!(get_feerate!(nodes[0]), feerate + 30);
3860 assert_eq!(get_feerate!(nodes[1]), feerate + 30);
3861 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3865 fn fake_network_test() {
3866 // Simple test which builds a network of ChannelManagers, connects them to each other, and
3867 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
3868 let nodes = create_network(4);
3870 // Create some initial channels
3871 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3872 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3873 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
3875 // Rebalance the network a bit by relaying one payment through all the channels...
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);
3879 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3881 // Send some more payments
3882 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
3883 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
3884 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
3886 // Test failure packets
3887 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
3888 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
3890 // Add a new channel that skips 3
3891 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
3893 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
3894 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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);
3899 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3901 // Do some rebalance loop payments, simultaneously
3902 let mut hops = Vec::with_capacity(3);
3903 hops.push(RouteHop {
3904 pubkey: nodes[2].node.get_our_node_id(),
3905 short_channel_id: chan_2.0.contents.short_channel_id,
3907 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
3909 hops.push(RouteHop {
3910 pubkey: nodes[3].node.get_our_node_id(),
3911 short_channel_id: chan_3.0.contents.short_channel_id,
3913 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
3915 hops.push(RouteHop {
3916 pubkey: nodes[1].node.get_our_node_id(),
3917 short_channel_id: chan_4.0.contents.short_channel_id,
3919 cltv_expiry_delta: TEST_FINAL_CLTV,
3921 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;
3922 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;
3923 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
3925 let mut hops = Vec::with_capacity(3);
3926 hops.push(RouteHop {
3927 pubkey: nodes[3].node.get_our_node_id(),
3928 short_channel_id: chan_4.0.contents.short_channel_id,
3930 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
3932 hops.push(RouteHop {
3933 pubkey: nodes[2].node.get_our_node_id(),
3934 short_channel_id: chan_3.0.contents.short_channel_id,
3936 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
3938 hops.push(RouteHop {
3939 pubkey: nodes[1].node.get_our_node_id(),
3940 short_channel_id: chan_2.0.contents.short_channel_id,
3942 cltv_expiry_delta: TEST_FINAL_CLTV,
3944 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;
3945 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;
3946 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
3948 // Claim the rebalances...
3949 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
3950 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
3952 // Add a duplicate new channel from 2 to 4
3953 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
3955 // Send some payments across both channels
3956 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3957 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3958 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3960 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
3962 //TODO: Test that routes work again here as we've been notified that the channel is full
3964 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
3965 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
3966 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
3968 // Close down the channels...
3969 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
3970 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
3971 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
3972 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
3973 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
3977 fn duplicate_htlc_test() {
3978 // Test that we accept duplicate payment_hash HTLCs across the network and that
3979 // claiming/failing them are all separate and don't effect each other
3980 let mut nodes = create_network(6);
3982 // Create some initial channels to route via 3 to 4/5 from 0/1/2
3983 create_announced_chan_between_nodes(&nodes, 0, 3);
3984 create_announced_chan_between_nodes(&nodes, 1, 3);
3985 create_announced_chan_between_nodes(&nodes, 2, 3);
3986 create_announced_chan_between_nodes(&nodes, 3, 4);
3987 create_announced_chan_between_nodes(&nodes, 3, 5);
3989 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
3991 *nodes[0].network_payment_count.borrow_mut() -= 1;
3992 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
3994 *nodes[0].network_payment_count.borrow_mut() -= 1;
3995 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
3997 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
3998 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
3999 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
4002 #[derive(PartialEq)]
4003 enum HTLCType { NONE, TIMEOUT, SUCCESS }
4004 /// Tests that the given node has broadcast transactions for the given Channel
4006 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
4007 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
4008 /// broadcast and the revoked outputs were claimed.
4010 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
4011 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
4013 /// All broadcast transactions must be accounted for in one of the above three types of we'll
4015 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
4016 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4017 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
4019 let mut res = Vec::with_capacity(2);
4020 node_txn.retain(|tx| {
4021 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
4022 check_spends!(tx, chan.3.clone());
4023 if commitment_tx.is_none() {
4024 res.push(tx.clone());
4029 if let Some(explicit_tx) = commitment_tx {
4030 res.push(explicit_tx.clone());
4033 assert_eq!(res.len(), 1);
4035 if has_htlc_tx != HTLCType::NONE {
4036 node_txn.retain(|tx| {
4037 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
4038 check_spends!(tx, res[0].clone());
4039 if has_htlc_tx == HTLCType::TIMEOUT {
4040 assert!(tx.lock_time != 0);
4042 assert!(tx.lock_time == 0);
4044 res.push(tx.clone());
4048 assert_eq!(res.len(), 2);
4051 assert!(node_txn.is_empty());
4055 /// Tests that the given node has broadcast a claim transaction against the provided revoked
4056 /// HTLC transaction.
4057 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
4058 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4059 assert_eq!(node_txn.len(), 1);
4060 node_txn.retain(|tx| {
4061 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
4062 check_spends!(tx, revoked_tx.clone());
4066 assert!(node_txn.is_empty());
4069 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
4070 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4072 assert!(node_txn.len() >= 1);
4073 assert_eq!(node_txn[0].input.len(), 1);
4074 let mut found_prev = false;
4076 for tx in prev_txn {
4077 if node_txn[0].input[0].previous_output.txid == tx.txid() {
4078 check_spends!(node_txn[0], tx.clone());
4079 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
4080 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
4086 assert!(found_prev);
4088 let mut res = Vec::new();
4089 mem::swap(&mut *node_txn, &mut res);
4093 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
4094 let events_1 = nodes[a].node.get_and_clear_pending_events();
4095 assert_eq!(events_1.len(), 1);
4096 let as_update = match events_1[0] {
4097 Event::BroadcastChannelUpdate { ref msg } => {
4100 _ => panic!("Unexpected event"),
4103 let events_2 = nodes[b].node.get_and_clear_pending_events();
4104 assert_eq!(events_2.len(), 1);
4105 let bs_update = match events_2[0] {
4106 Event::BroadcastChannelUpdate { ref msg } => {
4109 _ => panic!("Unexpected event"),
4113 node.router.handle_channel_update(&as_update).unwrap();
4114 node.router.handle_channel_update(&bs_update).unwrap();
4119 fn channel_reserve_test() {
4121 use std::sync::atomic::Ordering;
4122 use ln::msgs::HandleError;
4124 macro_rules! get_channel_value_stat {
4125 ($node: expr, $channel_id: expr) => {{
4126 let chan_lock = $node.node.channel_state.lock().unwrap();
4127 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
4128 chan.get_value_stat()
4132 let mut nodes = create_network(3);
4133 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
4134 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
4136 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
4137 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
4139 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
4140 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
4142 macro_rules! get_route_and_payment_hash {
4143 ($recv_value: expr) => {{
4144 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
4145 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4146 (route, payment_hash, payment_preimage)
4150 macro_rules! expect_pending_htlcs_forwardable {
4152 let events = $node.node.get_and_clear_pending_events();
4153 assert_eq!(events.len(), 1);
4155 Event::PendingHTLCsForwardable { .. } => { },
4156 _ => panic!("Unexpected event"),
4158 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4159 $node.node.process_pending_htlc_forwards();
4163 macro_rules! expect_forward {
4165 let mut events = $node.node.get_and_clear_pending_events();
4166 assert_eq!(events.len(), 1);
4167 check_added_monitors!($node, 1);
4168 let payment_event = SendEvent::from_event(events.remove(0));
4173 macro_rules! expect_payment_received {
4174 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
4175 let events = $node.node.get_and_clear_pending_events();
4176 assert_eq!(events.len(), 1);
4178 Event::PaymentReceived { ref payment_hash, amt } => {
4179 assert_eq!($expected_payment_hash, *payment_hash);
4180 assert_eq!($expected_recv_value, amt);
4182 _ => panic!("Unexpected event"),
4187 let feemsat = 239; // somehow we know?
4188 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
4190 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
4192 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
4194 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
4195 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
4196 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
4198 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4199 _ => panic!("Unknown error variants"),
4203 let mut htlc_id = 0;
4204 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
4205 // nodes[0]'s wealth
4207 let amt_msat = recv_value_0 + total_fee_msat;
4208 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
4211 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
4214 let (stat01_, stat11_, stat12_, stat22_) = (
4215 get_channel_value_stat!(nodes[0], chan_1.2),
4216 get_channel_value_stat!(nodes[1], chan_1.2),
4217 get_channel_value_stat!(nodes[1], chan_2.2),
4218 get_channel_value_stat!(nodes[2], chan_2.2),
4221 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
4222 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
4223 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
4224 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
4225 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
4229 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
4230 // attempt to get channel_reserve violation
4231 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
4232 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
4234 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4235 _ => panic!("Unknown error variants"),
4239 // adding pending output
4240 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
4241 let amt_msat_1 = recv_value_1 + total_fee_msat;
4243 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
4244 let payment_event_1 = {
4245 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
4246 check_added_monitors!(nodes[0], 1);
4248 let mut events = nodes[0].node.get_and_clear_pending_events();
4249 assert_eq!(events.len(), 1);
4250 SendEvent::from_event(events.remove(0))
4252 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
4254 // channel reserve test with htlc pending output > 0
4255 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
4257 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4258 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4259 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4260 _ => panic!("Unknown error variants"),
4265 // test channel_reserve test on nodes[1] side
4266 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4268 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
4269 let secp_ctx = Secp256k1::new();
4270 let session_priv = SecretKey::from_slice(&secp_ctx, &{
4271 let mut session_key = [0; 32];
4272 rng::fill_bytes(&mut session_key);
4274 }).expect("RNG is bad!");
4276 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4277 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
4278 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
4279 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
4280 let msg = msgs::UpdateAddHTLC {
4281 channel_id: chan_1.2,
4283 amount_msat: htlc_msat,
4284 payment_hash: our_payment_hash,
4285 cltv_expiry: htlc_cltv,
4286 onion_routing_packet: onion_packet,
4289 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
4291 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
4295 // split the rest to test holding cell
4296 let recv_value_21 = recv_value_2/2;
4297 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
4299 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
4300 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);
4303 // now see if they go through on both sides
4304 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
4305 // but this will stuck in the holding cell
4306 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
4307 check_added_monitors!(nodes[0], 0);
4308 let events = nodes[0].node.get_and_clear_pending_events();
4309 assert_eq!(events.len(), 0);
4311 // test with outbound holding cell amount > 0
4313 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
4314 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4315 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4316 _ => panic!("Unknown error variants"),
4320 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
4321 // this will also stuck in the holding cell
4322 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
4323 check_added_monitors!(nodes[0], 0);
4324 let events = nodes[0].node.get_and_clear_pending_events();
4325 assert_eq!(events.len(), 0);
4327 // flush the pending htlc
4328 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();
4329 check_added_monitors!(nodes[1], 1);
4331 let commitment_update_2 = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap().unwrap();
4332 check_added_monitors!(nodes[0], 1);
4333 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();
4334 assert!(bs_none.is_none());
4335 check_added_monitors!(nodes[0], 1);
4336 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
4337 check_added_monitors!(nodes[1], 1);
4339 expect_pending_htlcs_forwardable!(nodes[1]);
4341 let ref payment_event_11 = expect_forward!(nodes[1]);
4342 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
4343 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
4345 expect_pending_htlcs_forwardable!(nodes[2]);
4346 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
4348 // flush the htlcs in the holding cell
4349 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
4350 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
4351 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
4352 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
4353 expect_pending_htlcs_forwardable!(nodes[1]);
4355 let ref payment_event_3 = expect_forward!(nodes[1]);
4356 assert_eq!(payment_event_3.msgs.len(), 2);
4357 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
4358 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
4360 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
4361 expect_pending_htlcs_forwardable!(nodes[2]);
4363 let events = nodes[2].node.get_and_clear_pending_events();
4364 assert_eq!(events.len(), 2);
4366 Event::PaymentReceived { ref payment_hash, amt } => {
4367 assert_eq!(our_payment_hash_21, *payment_hash);
4368 assert_eq!(recv_value_21, amt);
4370 _ => panic!("Unexpected event"),
4373 Event::PaymentReceived { ref payment_hash, amt } => {
4374 assert_eq!(our_payment_hash_22, *payment_hash);
4375 assert_eq!(recv_value_22, amt);
4377 _ => panic!("Unexpected event"),
4380 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
4381 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
4382 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
4384 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);
4385 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
4386 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
4387 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
4389 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
4390 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
4394 fn channel_monitor_network_test() {
4395 // Simple test which builds a network of ChannelManagers, connects them to each other, and
4396 // tests that ChannelMonitor is able to recover from various states.
4397 let nodes = create_network(5);
4399 // Create some initial channels
4400 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4401 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4402 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4403 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4405 // Rebalance the network a bit by relaying one payment through all the channels...
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);
4409 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4411 // Simple case with no pending HTLCs:
4412 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
4414 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
4415 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4416 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4417 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
4419 get_announce_close_broadcast_events(&nodes, 0, 1);
4420 assert_eq!(nodes[0].node.list_channels().len(), 0);
4421 assert_eq!(nodes[1].node.list_channels().len(), 1);
4423 // One pending HTLC is discarded by the force-close:
4424 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
4426 // Simple case of one pending HTLC to HTLC-Timeout
4427 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
4429 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
4430 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4431 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4432 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
4434 get_announce_close_broadcast_events(&nodes, 1, 2);
4435 assert_eq!(nodes[1].node.list_channels().len(), 0);
4436 assert_eq!(nodes[2].node.list_channels().len(), 1);
4438 macro_rules! claim_funds {
4439 ($node: expr, $prev_node: expr, $preimage: expr) => {
4441 assert!($node.node.claim_funds($preimage));
4442 check_added_monitors!($node, 1);
4444 let events = $node.node.get_and_clear_pending_events();
4445 assert_eq!(events.len(), 1);
4447 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
4448 assert!(update_add_htlcs.is_empty());
4449 assert!(update_fail_htlcs.is_empty());
4450 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
4452 _ => panic!("Unexpected event"),
4458 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
4459 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
4460 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
4462 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
4464 // Claim the payment on nodes[3], giving it knowledge of the preimage
4465 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
4467 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4468 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
4470 check_preimage_claim(&nodes[3], &node_txn);
4472 get_announce_close_broadcast_events(&nodes, 2, 3);
4473 assert_eq!(nodes[2].node.list_channels().len(), 0);
4474 assert_eq!(nodes[3].node.list_channels().len(), 1);
4476 { // Cheat and reset nodes[4]'s height to 1
4477 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4478 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
4481 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
4482 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
4483 // One pending HTLC to time out:
4484 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
4485 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
4489 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4490 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4491 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
4492 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4493 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4496 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
4498 // Claim the payment on nodes[4], giving it knowledge of the preimage
4499 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
4501 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4502 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4503 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
4504 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4505 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4508 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
4510 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4511 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
4513 check_preimage_claim(&nodes[4], &node_txn);
4515 get_announce_close_broadcast_events(&nodes, 3, 4);
4516 assert_eq!(nodes[3].node.list_channels().len(), 0);
4517 assert_eq!(nodes[4].node.list_channels().len(), 0);
4519 // Create some new channels:
4520 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
4522 // A pending HTLC which will be revoked:
4523 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4524 // Get the will-be-revoked local txn from nodes[0]
4525 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
4526 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
4527 assert_eq!(revoked_local_txn[0].input.len(), 1);
4528 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
4529 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
4530 assert_eq!(revoked_local_txn[1].input.len(), 1);
4531 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4532 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4533 // Revoke the old state
4534 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
4537 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4538 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4540 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4541 assert_eq!(node_txn.len(), 3);
4542 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
4543 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
4545 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4546 node_txn.swap_remove(0);
4548 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
4550 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4551 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
4552 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4553 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
4554 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
4556 get_announce_close_broadcast_events(&nodes, 0, 1);
4557 assert_eq!(nodes[0].node.list_channels().len(), 0);
4558 assert_eq!(nodes[1].node.list_channels().len(), 0);
4562 fn revoked_output_claim() {
4563 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
4564 // transaction is broadcast by its counterparty
4565 let nodes = create_network(2);
4566 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4567 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
4568 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4569 assert_eq!(revoked_local_txn.len(), 1);
4570 // Only output is the full channel value back to nodes[0]:
4571 assert_eq!(revoked_local_txn[0].output.len(), 1);
4572 // Send a payment through, updating everyone's latest commitment txn
4573 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
4575 // Inform nodes[1] that nodes[0] broadcast a stale tx
4576 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4577 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4578 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4579 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
4581 assert_eq!(node_txn[0], node_txn[2]);
4583 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4584 check_spends!(node_txn[1], chan_1.3.clone());
4586 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
4587 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4588 get_announce_close_broadcast_events(&nodes, 0, 1);
4592 fn claim_htlc_outputs_shared_tx() {
4593 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
4594 let nodes = create_network(2);
4596 // Create some new channel:
4597 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4599 // Rebalance the network to generate htlc in the two directions
4600 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4601 // 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
4602 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4603 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4605 // Get the will-be-revoked local txn from node[0]
4606 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4607 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
4608 assert_eq!(revoked_local_txn[0].input.len(), 1);
4609 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4610 assert_eq!(revoked_local_txn[1].input.len(), 1);
4611 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4612 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4613 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
4615 //Revoke the old state
4616 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4619 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4621 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4623 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4624 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4625 assert_eq!(node_txn.len(), 4);
4627 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
4628 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4630 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
4632 let mut witness_lens = BTreeSet::new();
4633 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4634 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
4635 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
4636 assert_eq!(witness_lens.len(), 3);
4637 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4638 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4639 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4641 // Next nodes[1] broadcasts its current local tx state:
4642 assert_eq!(node_txn[1].input.len(), 1);
4643 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
4645 assert_eq!(node_txn[2].input.len(), 1);
4646 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
4647 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4648 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
4649 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4650 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
4652 get_announce_close_broadcast_events(&nodes, 0, 1);
4653 assert_eq!(nodes[0].node.list_channels().len(), 0);
4654 assert_eq!(nodes[1].node.list_channels().len(), 0);
4658 fn claim_htlc_outputs_single_tx() {
4659 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
4660 let nodes = create_network(2);
4662 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4664 // Rebalance the network to generate htlc in the two directions
4665 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4666 // 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
4667 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
4668 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4669 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4671 // Get the will-be-revoked local txn from node[0]
4672 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4674 //Revoke the old state
4675 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4678 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4680 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4682 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4683 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4684 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)
4686 assert_eq!(node_txn[0], node_txn[7]);
4687 assert_eq!(node_txn[1], node_txn[8]);
4688 assert_eq!(node_txn[2], node_txn[9]);
4689 assert_eq!(node_txn[3], node_txn[10]);
4690 assert_eq!(node_txn[4], node_txn[11]);
4691 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
4692 assert_eq!(node_txn[4], node_txn[6]);
4694 assert_eq!(node_txn[0].input.len(), 1);
4695 assert_eq!(node_txn[1].input.len(), 1);
4696 assert_eq!(node_txn[2].input.len(), 1);
4698 let mut revoked_tx_map = HashMap::new();
4699 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
4700 node_txn[0].verify(&revoked_tx_map).unwrap();
4701 node_txn[1].verify(&revoked_tx_map).unwrap();
4702 node_txn[2].verify(&revoked_tx_map).unwrap();
4704 let mut witness_lens = BTreeSet::new();
4705 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4706 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
4707 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
4708 assert_eq!(witness_lens.len(), 3);
4709 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4710 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4711 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4713 assert_eq!(node_txn[3].input.len(), 1);
4714 check_spends!(node_txn[3], chan_1.3.clone());
4716 assert_eq!(node_txn[4].input.len(), 1);
4717 let witness_script = node_txn[4].input[0].witness.last().unwrap();
4718 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4719 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
4720 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4721 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
4723 get_announce_close_broadcast_events(&nodes, 0, 1);
4724 assert_eq!(nodes[0].node.list_channels().len(), 0);
4725 assert_eq!(nodes[1].node.list_channels().len(), 0);
4729 fn test_htlc_ignore_latest_remote_commitment() {
4730 // Test that HTLC transactions spending the latest remote commitment transaction are simply
4731 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
4732 let nodes = create_network(2);
4733 create_announced_chan_between_nodes(&nodes, 0, 1);
4735 route_payment(&nodes[0], &[&nodes[1]], 10000000);
4736 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
4738 let events = nodes[0].node.get_and_clear_pending_events();
4739 assert_eq!(events.len(), 1);
4741 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4742 assert_eq!(flags & 0b10, 0b10);
4744 _ => panic!("Unexpected event"),
4748 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4749 assert_eq!(node_txn.len(), 2);
4751 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4752 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4755 let events = nodes[1].node.get_and_clear_pending_events();
4756 assert_eq!(events.len(), 1);
4758 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4759 assert_eq!(flags & 0b10, 0b10);
4761 _ => panic!("Unexpected event"),
4765 // Duplicate the block_connected call since this may happen due to other listeners
4766 // registering new transactions
4767 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4771 fn test_force_close_fail_back() {
4772 // Check which HTLCs are failed-backwards on channel force-closure
4773 let mut nodes = create_network(3);
4774 create_announced_chan_between_nodes(&nodes, 0, 1);
4775 create_announced_chan_between_nodes(&nodes, 1, 2);
4777 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
4779 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4781 let mut payment_event = {
4782 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4783 check_added_monitors!(nodes[0], 1);
4785 let mut events = nodes[0].node.get_and_clear_pending_events();
4786 assert_eq!(events.len(), 1);
4787 SendEvent::from_event(events.remove(0))
4790 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4791 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4793 let events_1 = nodes[1].node.get_and_clear_pending_events();
4794 assert_eq!(events_1.len(), 1);
4796 Event::PendingHTLCsForwardable { .. } => { },
4797 _ => panic!("Unexpected event"),
4800 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
4801 nodes[1].node.process_pending_htlc_forwards();
4803 let mut events_2 = nodes[1].node.get_and_clear_pending_events();
4804 assert_eq!(events_2.len(), 1);
4805 payment_event = SendEvent::from_event(events_2.remove(0));
4806 assert_eq!(payment_event.msgs.len(), 1);
4808 check_added_monitors!(nodes[1], 1);
4809 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4810 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
4811 check_added_monitors!(nodes[2], 1);
4813 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
4814 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
4815 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
4817 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
4818 let events_3 = nodes[2].node.get_and_clear_pending_events();
4819 assert_eq!(events_3.len(), 1);
4821 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4822 assert_eq!(flags & 0b10, 0b10);
4824 _ => panic!("Unexpected event"),
4828 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4829 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
4830 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
4831 // back to nodes[1] upon timeout otherwise.
4832 assert_eq!(node_txn.len(), 1);
4836 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4837 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4839 let events_4 = nodes[1].node.get_and_clear_pending_events();
4840 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
4841 assert_eq!(events_4.len(), 1);
4843 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4844 assert_eq!(flags & 0b10, 0b10);
4846 _ => panic!("Unexpected event"),
4849 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
4851 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
4852 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
4853 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
4855 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4856 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4857 assert_eq!(node_txn.len(), 1);
4858 assert_eq!(node_txn[0].input.len(), 1);
4859 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
4860 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
4861 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
4863 check_spends!(node_txn[0], tx);
4867 fn test_unconf_chan() {
4868 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
4869 let nodes = create_network(2);
4870 create_announced_chan_between_nodes(&nodes, 0, 1);
4872 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4873 assert_eq!(channel_state.by_id.len(), 1);
4874 assert_eq!(channel_state.short_to_id.len(), 1);
4875 mem::drop(channel_state);
4877 let mut headers = Vec::new();
4878 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4879 headers.push(header.clone());
4881 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4882 headers.push(header.clone());
4884 while !headers.is_empty() {
4885 nodes[0].node.block_disconnected(&headers.pop().unwrap());
4888 let events = nodes[0].node.get_and_clear_pending_events();
4889 assert_eq!(events.len(), 1);
4891 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4892 assert_eq!(flags & 0b10, 0b10);
4894 _ => panic!("Unexpected event"),
4897 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4898 assert_eq!(channel_state.by_id.len(), 0);
4899 assert_eq!(channel_state.short_to_id.len(), 0);
4902 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
4903 /// for claims/fails they are separated out.
4904 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)) {
4905 let reestablish_1 = node_a.node.peer_connected(&node_b.node.get_our_node_id());
4906 let reestablish_2 = node_b.node.peer_connected(&node_a.node.get_our_node_id());
4908 let mut resp_1 = Vec::new();
4909 for msg in reestablish_1 {
4910 resp_1.push(node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap());
4912 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4913 check_added_monitors!(node_b, 1);
4915 check_added_monitors!(node_b, 0);
4918 let mut resp_2 = Vec::new();
4919 for msg in reestablish_2 {
4920 resp_2.push(node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap());
4922 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4923 check_added_monitors!(node_a, 1);
4925 check_added_monitors!(node_a, 0);
4928 // We dont yet support both needing updates, as that would require a different commitment dance:
4929 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
4930 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
4932 for chan_msgs in resp_1.drain(..) {
4934 let a = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
4935 let _announcement_sigs_opt = a.unwrap();
4936 //TODO: Test announcement_sigs re-sending when we've implemented it
4938 assert!(chan_msgs.0.is_none());
4941 assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
4942 assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4943 check_added_monitors!(node_a, 1);
4945 assert!(chan_msgs.1.is_none());
4947 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4948 let commitment_update = chan_msgs.2.unwrap();
4949 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4950 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
4952 assert!(commitment_update.update_add_htlcs.is_empty());
4954 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
4955 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
4956 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4957 for update_add in commitment_update.update_add_htlcs {
4958 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
4960 for update_fulfill in commitment_update.update_fulfill_htlcs {
4961 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
4963 for update_fail in commitment_update.update_fail_htlcs {
4964 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
4967 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4968 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
4970 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();
4971 check_added_monitors!(node_a, 1);
4972 assert!(as_commitment_signed.is_none());
4973 assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
4974 check_added_monitors!(node_b, 1);
4977 assert!(chan_msgs.2.is_none());
4981 for chan_msgs in resp_2.drain(..) {
4983 let _announcement_sigs_opt = node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
4984 //TODO: Test announcement_sigs re-sending when we've implemented it
4986 assert!(chan_msgs.0.is_none());
4989 assert!(chan_msgs.3 == msgs::RAACommitmentOrder::RevokeAndACKFirst);
4990 assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4991 check_added_monitors!(node_b, 1);
4993 assert!(chan_msgs.1.is_none());
4995 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4996 let commitment_update = chan_msgs.2.unwrap();
4997 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
4998 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
5000 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
5001 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
5002 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
5003 for update_add in commitment_update.update_add_htlcs {
5004 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
5006 for update_fulfill in commitment_update.update_fulfill_htlcs {
5007 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
5009 for update_fail in commitment_update.update_fail_htlcs {
5010 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
5013 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
5014 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
5016 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();
5017 check_added_monitors!(node_b, 1);
5018 assert!(bs_commitment_signed.is_none());
5019 assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5020 check_added_monitors!(node_a, 1);
5023 assert!(chan_msgs.2.is_none());
5029 fn test_simple_peer_disconnect() {
5030 // Test that we can reconnect when there are no lost messages
5031 let nodes = create_network(3);
5032 create_announced_chan_between_nodes(&nodes, 0, 1);
5033 create_announced_chan_between_nodes(&nodes, 1, 2);
5035 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5036 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5037 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5039 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5040 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5041 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
5042 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
5044 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5045 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5046 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5048 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5049 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
5050 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5051 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
5053 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5054 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5056 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
5057 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
5059 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
5061 let events = nodes[0].node.get_and_clear_pending_events();
5062 assert_eq!(events.len(), 2);
5064 Event::PaymentSent { payment_preimage } => {
5065 assert_eq!(payment_preimage, payment_preimage_3);
5067 _ => panic!("Unexpected event"),
5070 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
5071 assert_eq!(payment_hash, payment_hash_5);
5072 assert!(rejected_by_dest);
5074 _ => panic!("Unexpected event"),
5078 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
5079 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
5082 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
5083 // Test that we can reconnect when in-flight HTLC updates get dropped
5084 let mut nodes = create_network(2);
5085 if messages_delivered == 0 {
5086 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
5087 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
5089 create_announced_chan_between_nodes(&nodes, 0, 1);
5092 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();
5093 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
5095 let payment_event = {
5096 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
5097 check_added_monitors!(nodes[0], 1);
5099 let mut events = nodes[0].node.get_and_clear_pending_events();
5100 assert_eq!(events.len(), 1);
5101 SendEvent::from_event(events.remove(0))
5103 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
5105 if messages_delivered < 2 {
5106 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
5108 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5109 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();
5110 check_added_monitors!(nodes[1], 1);
5112 if messages_delivered >= 3 {
5113 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5114 check_added_monitors!(nodes[0], 1);
5116 if messages_delivered >= 4 {
5117 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();
5118 assert!(as_commitment_signed.is_none());
5119 check_added_monitors!(nodes[0], 1);
5121 if messages_delivered >= 5 {
5122 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
5123 check_added_monitors!(nodes[1], 1);
5129 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5130 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5131 if messages_delivered < 2 {
5132 // Even if the funding_locked messages get exchanged, as long as nothing further was
5133 // received on either side, both sides will need to resend them.
5134 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
5135 } else if messages_delivered == 2 {
5136 // nodes[0] still wants its RAA + commitment_signed
5137 reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
5138 } else if messages_delivered == 3 {
5139 // nodes[0] still wants its commitment_signed
5140 reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
5141 } else if messages_delivered == 4 {
5142 // nodes[1] still wants its final RAA
5143 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
5144 } else if messages_delivered == 5 {
5145 // Everything was delivered...
5146 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5149 let events_1 = nodes[1].node.get_and_clear_pending_events();
5150 assert_eq!(events_1.len(), 1);
5152 Event::PendingHTLCsForwardable { .. } => { },
5153 _ => panic!("Unexpected event"),
5156 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5157 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5158 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5160 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
5161 nodes[1].node.process_pending_htlc_forwards();
5163 let events_2 = nodes[1].node.get_and_clear_pending_events();
5164 assert_eq!(events_2.len(), 1);
5166 Event::PaymentReceived { ref payment_hash, amt } => {
5167 assert_eq!(payment_hash_1, *payment_hash);
5168 assert_eq!(amt, 1000000);
5170 _ => panic!("Unexpected event"),
5173 nodes[1].node.claim_funds(payment_preimage_1);
5174 check_added_monitors!(nodes[1], 1);
5176 let events_3 = nodes[1].node.get_and_clear_pending_events();
5177 assert_eq!(events_3.len(), 1);
5178 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
5179 Event::UpdateHTLCs { ref node_id, ref updates } => {
5180 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5181 assert!(updates.update_add_htlcs.is_empty());
5182 assert!(updates.update_fail_htlcs.is_empty());
5183 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5184 assert!(updates.update_fail_malformed_htlcs.is_empty());
5185 assert!(updates.update_fee.is_none());
5186 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
5188 _ => panic!("Unexpected event"),
5191 if messages_delivered >= 1 {
5192 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
5194 let events_4 = nodes[0].node.get_and_clear_pending_events();
5195 assert_eq!(events_4.len(), 1);
5197 Event::PaymentSent { ref payment_preimage } => {
5198 assert_eq!(payment_preimage_1, *payment_preimage);
5200 _ => panic!("Unexpected event"),
5203 if messages_delivered >= 2 {
5204 let (as_revoke_and_ack, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
5205 check_added_monitors!(nodes[0], 1);
5207 if messages_delivered >= 3 {
5208 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
5209 check_added_monitors!(nodes[1], 1);
5211 if messages_delivered >= 4 {
5212 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();
5213 assert!(bs_commitment_signed.is_none());
5214 check_added_monitors!(nodes[1], 1);
5216 if messages_delivered >= 5 {
5217 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5218 check_added_monitors!(nodes[0], 1);
5225 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5226 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5227 if messages_delivered < 2 {
5228 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
5229 //TODO: Deduplicate PaymentSent events, then enable this if:
5230 //if messages_delivered < 1 {
5231 let events_4 = nodes[0].node.get_and_clear_pending_events();
5232 assert_eq!(events_4.len(), 1);
5234 Event::PaymentSent { ref payment_preimage } => {
5235 assert_eq!(payment_preimage_1, *payment_preimage);
5237 _ => panic!("Unexpected event"),
5240 } else if messages_delivered == 2 {
5241 // nodes[0] still wants its RAA + commitment_signed
5242 reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
5243 } else if messages_delivered == 3 {
5244 // nodes[0] still wants its commitment_signed
5245 reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
5246 } else if messages_delivered == 4 {
5247 // nodes[1] still wants its final RAA
5248 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
5249 } else if messages_delivered == 5 {
5250 // Everything was delivered...
5251 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5254 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5255 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5256 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5258 // Channel should still work fine...
5259 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
5260 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
5264 fn test_drop_messages_peer_disconnect_a() {
5265 do_test_drop_messages_peer_disconnect(0);
5266 do_test_drop_messages_peer_disconnect(1);
5267 do_test_drop_messages_peer_disconnect(2);
5271 fn test_drop_messages_peer_disconnect_b() {
5272 do_test_drop_messages_peer_disconnect(3);
5273 do_test_drop_messages_peer_disconnect(4);
5274 do_test_drop_messages_peer_disconnect(5);
5278 fn test_funding_peer_disconnect() {
5279 // Test that we can lock in our funding tx while disconnected
5280 let nodes = create_network(2);
5281 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
5283 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5284 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5286 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
5287 let events_1 = nodes[0].node.get_and_clear_pending_events();
5288 assert_eq!(events_1.len(), 1);
5290 Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5291 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5292 assert!(announcement_sigs.is_none());
5294 _ => panic!("Unexpected event"),
5297 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
5298 let events_2 = nodes[1].node.get_and_clear_pending_events();
5299 assert_eq!(events_2.len(), 1);
5301 Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5302 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5303 assert!(announcement_sigs.is_none());
5305 _ => panic!("Unexpected event"),
5308 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5309 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5310 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5311 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5313 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
5314 // rebroadcasting announcement_signatures upon reconnect.
5316 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();
5317 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
5318 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
5322 fn test_invalid_channel_announcement() {
5323 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
5324 let secp_ctx = Secp256k1::new();
5325 let nodes = create_network(2);
5327 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
5329 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
5330 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
5331 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5332 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5334 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 } );
5336 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
5337 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
5339 let as_network_key = nodes[0].node.get_our_node_id();
5340 let bs_network_key = nodes[1].node.get_our_node_id();
5342 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
5344 let mut chan_announcement;
5346 macro_rules! dummy_unsigned_msg {
5348 msgs::UnsignedChannelAnnouncement {
5349 features: msgs::GlobalFeatures::new(),
5350 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
5351 short_channel_id: as_chan.get_short_channel_id().unwrap(),
5352 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
5353 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
5354 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
5355 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
5356 excess_data: Vec::new(),
5361 macro_rules! sign_msg {
5362 ($unsigned_msg: expr) => {
5363 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
5364 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
5365 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
5366 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
5367 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
5368 chan_announcement = msgs::ChannelAnnouncement {
5369 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
5370 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
5371 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
5372 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
5373 contents: $unsigned_msg
5378 let unsigned_msg = dummy_unsigned_msg!();
5379 sign_msg!(unsigned_msg);
5380 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
5381 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 } );
5383 // Configured with Network::Testnet
5384 let mut unsigned_msg = dummy_unsigned_msg!();
5385 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
5386 sign_msg!(unsigned_msg);
5387 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
5389 let mut unsigned_msg = dummy_unsigned_msg!();
5390 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
5391 sign_msg!(unsigned_msg);
5392 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());