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::util::hash::{BitcoinHash, Sha256dHash};
17 use bitcoin_hashes::{Hash, HashEngine};
18 use bitcoin_hashes::hmac::{Hmac, HmacEngine};
19 use bitcoin_hashes::sha256::Hash as Sha256;
20 use bitcoin_hashes::cmp::fixed_time_eq;
22 use secp256k1::key::{SecretKey,PublicKey};
23 use secp256k1::{Secp256k1,Message};
24 use secp256k1::ecdh::SharedSecret;
27 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
28 use chain::transaction::OutPoint;
29 use ln::channel::{Channel, ChannelError};
30 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
31 use ln::router::Route;
34 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
35 use chain::keysinterface::KeysInterface;
36 use util::config::UserConfig;
37 use util::{byte_utils, events, rng};
38 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
39 use util::chacha20::ChaCha20;
40 use util::logger::Logger;
41 use util::errors::APIError;
45 use std::collections::{HashMap, hash_map, HashSet};
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
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 /// Stores the info we will need to send when we want to forward an HTLC onwards
64 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
65 pub(super) struct PendingForwardHTLCInfo {
66 onion_packet: Option<msgs::OnionPacket>,
67 incoming_shared_secret: [u8; 32],
68 payment_hash: PaymentHash,
69 short_channel_id: u64,
71 outgoing_cltv_value: u32,
74 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
75 pub(super) enum HTLCFailureMsg {
76 Relay(msgs::UpdateFailHTLC),
77 Malformed(msgs::UpdateFailMalformedHTLC),
80 /// Stores whether we can't forward an HTLC or relevant forwarding info
81 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
82 pub(super) enum PendingHTLCStatus {
83 Forward(PendingForwardHTLCInfo),
87 /// Tracks the inbound corresponding to an outbound HTLC
88 #[derive(Clone, PartialEq)]
89 pub(super) struct HTLCPreviousHopData {
90 short_channel_id: u64,
92 incoming_packet_shared_secret: [u8; 32],
95 /// Tracks the inbound corresponding to an outbound HTLC
96 #[derive(Clone, PartialEq)]
97 pub(super) enum HTLCSource {
98 PreviousHopData(HTLCPreviousHopData),
101 session_priv: SecretKey,
102 /// Technically we can recalculate this from the route, but we cache it here to avoid
103 /// doing a double-pass on route when we get a failure back
104 first_hop_htlc_msat: u64,
109 pub fn dummy() -> Self {
110 HTLCSource::OutboundRoute {
111 route: Route { hops: Vec::new() },
112 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
113 first_hop_htlc_msat: 0,
118 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
119 pub(super) enum HTLCFailReason {
121 err: msgs::OnionErrorPacket,
129 /// payment_hash type, use to cross-lock hop
130 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
131 pub struct PaymentHash(pub [u8;32]);
132 /// payment_preimage type, use to route payment between hop
133 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
134 pub struct PaymentPreimage(pub [u8;32]);
136 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
138 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
139 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
140 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
141 /// channel_state lock. We then return the set of things that need to be done outside the lock in
142 /// this struct and call handle_error!() on it.
144 struct MsgHandleErrInternal {
145 err: msgs::HandleError,
146 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
148 impl MsgHandleErrInternal {
150 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
154 action: Some(msgs::ErrorAction::SendErrorMessage {
155 msg: msgs::ErrorMessage {
157 data: err.to_string()
161 shutdown_finish: None,
165 fn from_no_close(err: msgs::HandleError) -> Self {
166 Self { err, shutdown_finish: None }
169 fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
173 action: Some(msgs::ErrorAction::SendErrorMessage {
174 msg: msgs::ErrorMessage {
176 data: err.to_string()
180 shutdown_finish: Some((shutdown_res, channel_update)),
184 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
187 ChannelError::Ignore(msg) => HandleError {
189 action: Some(msgs::ErrorAction::IgnoreError),
191 ChannelError::Close(msg) => HandleError {
193 action: Some(msgs::ErrorAction::SendErrorMessage {
194 msg: msgs::ErrorMessage {
196 data: msg.to_string()
201 shutdown_finish: None,
206 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
207 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
208 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
209 /// probably increase this significantly.
210 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
212 struct HTLCForwardInfo {
213 prev_short_channel_id: u64,
215 forward_info: PendingForwardHTLCInfo,
218 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
219 /// be sent in the order they appear in the return value, however sometimes the order needs to be
220 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
221 /// they were originally sent). In those cases, this enum is also returned.
222 #[derive(Clone, PartialEq)]
223 pub(super) enum RAACommitmentOrder {
224 /// Send the CommitmentUpdate messages first
226 /// Send the RevokeAndACK message first
230 struct ChannelHolder {
231 by_id: HashMap<[u8; 32], Channel>,
232 short_to_id: HashMap<u64, [u8; 32]>,
233 next_forward: Instant,
234 /// short channel id -> forward infos. Key of 0 means payments received
235 /// Note that while this is held in the same mutex as the channels themselves, no consistency
236 /// guarantees are made about there existing a channel with the short id here, nor the short
237 /// ids in the PendingForwardHTLCInfo!
238 forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
239 /// Note that while this is held in the same mutex as the channels themselves, no consistency
240 /// guarantees are made about the channels given here actually existing anymore by the time you
242 claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
243 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
244 /// for broadcast messages, where ordering isn't as strict).
245 pending_msg_events: Vec<events::MessageSendEvent>,
247 struct MutChannelHolder<'a> {
248 by_id: &'a mut HashMap<[u8; 32], Channel>,
249 short_to_id: &'a mut HashMap<u64, [u8; 32]>,
250 next_forward: &'a mut Instant,
251 forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
252 claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
253 pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
256 fn borrow_parts(&mut self) -> MutChannelHolder {
258 by_id: &mut self.by_id,
259 short_to_id: &mut self.short_to_id,
260 next_forward: &mut self.next_forward,
261 forward_htlcs: &mut self.forward_htlcs,
262 claimable_htlcs: &mut self.claimable_htlcs,
263 pending_msg_events: &mut self.pending_msg_events,
268 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
269 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
271 /// Manager which keeps track of a number of channels and sends messages to the appropriate
272 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
274 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
275 /// to individual Channels.
277 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
278 /// all peers during write/read (though does not modify this instance, only the instance being
279 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
280 /// called funding_transaction_generated for outbound channels).
282 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
283 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
284 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
285 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
286 /// the serialization process). If the deserialized version is out-of-date compared to the
287 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
288 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
290 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
291 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
292 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
293 /// block_connected() to step towards your best block) upon deserialization before using the
295 pub struct ChannelManager {
296 default_configuration: UserConfig,
297 genesis_hash: Sha256dHash,
298 fee_estimator: Arc<FeeEstimator>,
299 monitor: Arc<ManyChannelMonitor>,
300 chain_monitor: Arc<ChainWatchInterface>,
301 tx_broadcaster: Arc<BroadcasterInterface>,
303 latest_block_height: AtomicUsize,
304 last_block_hash: Mutex<Sha256dHash>,
305 secp_ctx: Secp256k1<secp256k1::All>,
307 channel_state: Mutex<ChannelHolder>,
308 our_network_key: SecretKey,
310 pending_events: Mutex<Vec<events::Event>>,
311 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
312 /// Essentially just when we're serializing ourselves out.
313 /// Taken first everywhere where we are making changes before any other locks.
314 total_consistency_lock: RwLock<()>,
316 keys_manager: Arc<KeysInterface>,
321 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
322 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
323 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
324 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
325 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
326 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
327 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
329 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
330 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
331 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
332 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
333 // on-chain to time out the HTLC.
336 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
338 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
339 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
342 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
344 macro_rules! secp_call {
345 ( $res: expr, $err: expr ) => {
348 Err(_) => return Err($err),
353 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
354 pub struct ChannelDetails {
355 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
356 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
357 /// Note that this means this value is *not* persistent - it can change once during the
358 /// lifetime of the channel.
359 pub channel_id: [u8; 32],
360 /// The position of the funding transaction in the chain. None if the funding transaction has
361 /// not yet been confirmed and the channel fully opened.
362 pub short_channel_id: Option<u64>,
363 /// The node_id of our counterparty
364 pub remote_network_id: PublicKey,
365 /// The value, in satoshis, of this channel as appears in the funding output
366 pub channel_value_satoshis: u64,
367 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
371 macro_rules! handle_error {
372 ($self: ident, $internal: expr, $their_node_id: expr) => {
375 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
376 if let Some((shutdown_res, update_option)) = shutdown_finish {
377 $self.finish_force_close_channel(shutdown_res);
378 if let Some(update) = update_option {
379 let mut channel_state = $self.channel_state.lock().unwrap();
380 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
391 macro_rules! break_chan_entry {
392 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
395 Err(ChannelError::Ignore(msg)) => {
396 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
398 Err(ChannelError::Close(msg)) => {
399 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
400 let (channel_id, mut chan) = $entry.remove_entry();
401 if let Some(short_id) = chan.get_short_channel_id() {
402 $channel_state.short_to_id.remove(&short_id);
404 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
410 macro_rules! try_chan_entry {
411 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
414 Err(ChannelError::Ignore(msg)) => {
415 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
417 Err(ChannelError::Close(msg)) => {
418 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
419 let (channel_id, mut chan) = $entry.remove_entry();
420 if let Some(short_id) = chan.get_short_channel_id() {
421 $channel_state.short_to_id.remove(&short_id);
423 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
429 macro_rules! return_monitor_err {
430 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
431 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
433 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
434 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
435 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
437 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
438 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
440 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
442 ChannelMonitorUpdateErr::PermanentFailure => {
443 let (channel_id, mut chan) = $entry.remove_entry();
444 if let Some(short_id) = chan.get_short_channel_id() {
445 $channel_state.short_to_id.remove(&short_id);
447 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
448 // chain in a confused state! We need to move them into the ChannelMonitor which
449 // will be responsible for failing backwards once things confirm on-chain.
450 // It's ok that we drop $failed_forwards here - at this point we'd rather they
451 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
452 // us bother trying to claim it just to forward on to another peer. If we're
453 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
454 // given up the preimage yet, so might as well just wait until the payment is
455 // retried, avoiding the on-chain fees.
456 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
458 ChannelMonitorUpdateErr::TemporaryFailure => {
459 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
460 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
466 // Does not break in case of TemporaryFailure!
467 macro_rules! maybe_break_monitor_err {
468 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
470 ChannelMonitorUpdateErr::PermanentFailure => {
471 let (channel_id, mut chan) = $entry.remove_entry();
472 if let Some(short_id) = chan.get_short_channel_id() {
473 $channel_state.short_to_id.remove(&short_id);
475 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
477 ChannelMonitorUpdateErr::TemporaryFailure => {
478 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
484 impl ChannelManager {
485 /// Constructs a new ChannelManager to hold several channels and route between them.
487 /// This is the main "logic hub" for all channel-related actions, and implements
488 /// ChannelMessageHandler.
490 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
492 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
493 pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig) -> Result<Arc<ChannelManager>, secp256k1::Error> {
494 let secp_ctx = Secp256k1::new();
496 let res = Arc::new(ChannelManager {
497 default_configuration: config.clone(),
498 genesis_hash: genesis_block(network).header.bitcoin_hash(),
499 fee_estimator: feeest.clone(),
500 monitor: monitor.clone(),
504 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
505 last_block_hash: Mutex::new(Default::default()),
508 channel_state: Mutex::new(ChannelHolder{
509 by_id: HashMap::new(),
510 short_to_id: HashMap::new(),
511 next_forward: Instant::now(),
512 forward_htlcs: HashMap::new(),
513 claimable_htlcs: HashMap::new(),
514 pending_msg_events: Vec::new(),
516 our_network_key: keys_manager.get_node_secret(),
518 pending_events: Mutex::new(Vec::new()),
519 total_consistency_lock: RwLock::new(()),
525 let weak_res = Arc::downgrade(&res);
526 res.chain_monitor.register_listener(weak_res);
530 /// Creates a new outbound channel to the given remote node and with the given value.
532 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
533 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
534 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
535 /// may wish to avoid using 0 for user_id here.
537 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
538 /// PeerManager::process_events afterwards.
540 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
541 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
542 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
543 if channel_value_satoshis < 1000 {
544 return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
547 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
548 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
550 let _ = self.total_consistency_lock.read().unwrap();
551 let mut channel_state = self.channel_state.lock().unwrap();
552 match channel_state.by_id.entry(channel.channel_id()) {
553 hash_map::Entry::Occupied(_) => {
554 if cfg!(feature = "fuzztarget") {
555 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
557 panic!("RNG is bad???");
560 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
562 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
563 node_id: their_network_key,
569 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
570 /// more information.
571 pub fn list_channels(&self) -> Vec<ChannelDetails> {
572 let channel_state = self.channel_state.lock().unwrap();
573 let mut res = Vec::with_capacity(channel_state.by_id.len());
574 for (channel_id, channel) in channel_state.by_id.iter() {
575 res.push(ChannelDetails {
576 channel_id: (*channel_id).clone(),
577 short_channel_id: channel.get_short_channel_id(),
578 remote_network_id: channel.get_their_node_id(),
579 channel_value_satoshis: channel.get_value_satoshis(),
580 user_id: channel.get_user_id(),
586 /// Gets the list of usable channels, in random order. Useful as an argument to
587 /// Router::get_route to ensure non-announced channels are used.
588 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
589 let channel_state = self.channel_state.lock().unwrap();
590 let mut res = Vec::with_capacity(channel_state.by_id.len());
591 for (channel_id, channel) in channel_state.by_id.iter() {
592 // Note we use is_live here instead of usable which leads to somewhat confused
593 // internal/external nomenclature, but that's ok cause that's probably what the user
594 // really wanted anyway.
595 if channel.is_live() {
596 res.push(ChannelDetails {
597 channel_id: (*channel_id).clone(),
598 short_channel_id: channel.get_short_channel_id(),
599 remote_network_id: channel.get_their_node_id(),
600 channel_value_satoshis: channel.get_value_satoshis(),
601 user_id: channel.get_user_id(),
608 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
609 /// will be accepted on the given channel, and after additional timeout/the closing of all
610 /// pending HTLCs, the channel will be closed on chain.
612 /// May generate a SendShutdown message event on success, which should be relayed.
613 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
614 let _ = self.total_consistency_lock.read().unwrap();
616 let (mut failed_htlcs, chan_option) = {
617 let mut channel_state_lock = self.channel_state.lock().unwrap();
618 let channel_state = channel_state_lock.borrow_parts();
619 match channel_state.by_id.entry(channel_id.clone()) {
620 hash_map::Entry::Occupied(mut chan_entry) => {
621 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
622 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
623 node_id: chan_entry.get().get_their_node_id(),
626 if chan_entry.get().is_shutdown() {
627 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
628 channel_state.short_to_id.remove(&short_id);
630 (failed_htlcs, Some(chan_entry.remove_entry().1))
631 } else { (failed_htlcs, None) }
633 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
636 for htlc_source in failed_htlcs.drain(..) {
637 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
639 let chan_update = if let Some(chan) = chan_option {
640 if let Ok(update) = self.get_channel_update(&chan) {
645 if let Some(update) = chan_update {
646 let mut channel_state = self.channel_state.lock().unwrap();
647 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
656 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
657 let (local_txn, mut failed_htlcs) = shutdown_res;
658 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
659 for htlc_source in failed_htlcs.drain(..) {
660 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
662 for tx in local_txn {
663 self.tx_broadcaster.broadcast_transaction(&tx);
667 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
668 /// the chain and rejecting new HTLCs on the given channel.
669 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
670 let _ = self.total_consistency_lock.read().unwrap();
673 let mut channel_state_lock = self.channel_state.lock().unwrap();
674 let channel_state = channel_state_lock.borrow_parts();
675 if let Some(chan) = channel_state.by_id.remove(channel_id) {
676 if let Some(short_id) = chan.get_short_channel_id() {
677 channel_state.short_to_id.remove(&short_id);
684 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
685 self.finish_force_close_channel(chan.force_shutdown());
686 if let Ok(update) = self.get_channel_update(&chan) {
687 let mut channel_state = self.channel_state.lock().unwrap();
688 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
694 /// Force close all channels, immediately broadcasting the latest local commitment transaction
695 /// for each to the chain and rejecting new HTLCs on each.
696 pub fn force_close_all_channels(&self) {
697 for chan in self.list_channels() {
698 self.force_close_channel(&chan.channel_id);
702 const ZERO:[u8; 65] = [0; 65];
703 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
704 macro_rules! return_malformed_err {
705 ($msg: expr, $err_code: expr) => {
707 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
708 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
709 channel_id: msg.channel_id,
710 htlc_id: msg.htlc_id,
711 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
712 failure_code: $err_code,
713 })), self.channel_state.lock().unwrap());
718 if let Err(_) = msg.onion_routing_packet.public_key {
719 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
722 let shared_secret = {
723 let mut arr = [0; 32];
724 arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
727 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
729 if msg.onion_routing_packet.version != 0 {
730 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
731 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
732 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
733 //receiving node would have to brute force to figure out which version was put in the
734 //packet by the node that send us the message, in the case of hashing the hop_data, the
735 //node knows the HMAC matched, so they already know what is there...
736 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
739 let mut hmac = HmacEngine::<Sha256>::new(&mu);
740 hmac.input(&msg.onion_routing_packet.hop_data);
741 hmac.input(&msg.payment_hash.0[..]);
742 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
743 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
746 let mut channel_state = None;
747 macro_rules! return_err {
748 ($msg: expr, $err_code: expr, $data: expr) => {
750 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
751 if channel_state.is_none() {
752 channel_state = Some(self.channel_state.lock().unwrap());
754 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
755 channel_id: msg.channel_id,
756 htlc_id: msg.htlc_id,
757 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
758 })), channel_state.unwrap());
763 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
764 let next_hop_data = {
765 let mut decoded = [0; 65];
766 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
767 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
769 let error_code = match err {
770 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
771 _ => 0x2000 | 2, // Should never happen
773 return_err!("Unable to decode our hop data", error_code, &[0;0]);
779 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
781 // final_expiry_too_soon
782 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
783 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
785 // final_incorrect_htlc_amount
786 if next_hop_data.data.amt_to_forward > msg.amount_msat {
787 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
789 // final_incorrect_cltv_expiry
790 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
791 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
794 // Note that we could obviously respond immediately with an update_fulfill_htlc
795 // message, however that would leak that we are the recipient of this payment, so
796 // instead we stay symmetric with the forwarding case, only responding (after a
797 // delay) once they've send us a commitment_signed!
799 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
801 payment_hash: msg.payment_hash.clone(),
803 incoming_shared_secret: shared_secret,
804 amt_to_forward: next_hop_data.data.amt_to_forward,
805 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
808 let mut new_packet_data = [0; 20*65];
809 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
810 chacha.process(&ChannelManager::ZERO[..], &mut new_packet_data[19*65..]);
812 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
814 let blinding_factor = {
815 let mut sha = Sha256::engine();
816 sha.input(&new_pubkey.serialize()[..]);
817 sha.input(&shared_secret);
818 SecretKey::from_slice(&self.secp_ctx, &Sha256::from_engine(sha).into_inner()).expect("SHA-256 is broken?")
821 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
823 } else { Ok(new_pubkey) };
825 let outgoing_packet = msgs::OnionPacket {
828 hop_data: new_packet_data,
829 hmac: next_hop_data.hmac.clone(),
832 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
833 onion_packet: Some(outgoing_packet),
834 payment_hash: msg.payment_hash.clone(),
835 short_channel_id: next_hop_data.data.short_channel_id,
836 incoming_shared_secret: shared_secret,
837 amt_to_forward: next_hop_data.data.amt_to_forward,
838 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
842 channel_state = Some(self.channel_state.lock().unwrap());
843 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
844 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
845 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
846 let forwarding_id = match id_option {
847 None => { // unknown_next_peer
848 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
850 Some(id) => id.clone(),
852 if let Some((err, code, chan_update)) = loop {
853 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
855 // Note that we could technically not return an error yet here and just hope
856 // that the connection is reestablished or monitor updated by the time we get
857 // around to doing the actual forward, but better to fail early if we can and
858 // hopefully an attacker trying to path-trace payments cannot make this occur
859 // on a small/per-node/per-channel scale.
860 if !chan.is_live() { // channel_disabled
861 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
863 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
864 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
866 let fee = amt_to_forward.checked_mul(chan.get_fee_proportional_millionths() as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
867 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
868 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())));
870 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
871 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())));
873 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
874 // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
875 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
876 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
878 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
879 break Some(("CLTV expiry is too far in the future", 21, None));
884 let mut res = Vec::with_capacity(8 + 128);
885 if let Some(chan_update) = chan_update {
886 if code == 0x1000 | 11 || code == 0x1000 | 12 {
887 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
889 else if code == 0x1000 | 13 {
890 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
892 else if code == 0x1000 | 20 {
893 res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
895 res.extend_from_slice(&chan_update.encode_with_len()[..]);
897 return_err!(err, code, &res[..]);
902 (pending_forward_info, channel_state.unwrap())
905 /// only fails if the channel does not yet have an assigned short_id
906 /// May be called with channel_state already locked!
907 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
908 let short_channel_id = match chan.get_short_channel_id() {
909 None => return Err(HandleError{err: "Channel not yet established", action: None}),
913 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
915 let unsigned = msgs::UnsignedChannelUpdate {
916 chain_hash: self.genesis_hash,
917 short_channel_id: short_channel_id,
918 timestamp: chan.get_channel_update_count(),
919 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
920 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
921 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
922 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
923 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
924 excess_data: Vec::new(),
927 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
928 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
930 Ok(msgs::ChannelUpdate {
936 /// Sends a payment along a given route.
938 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
939 /// fields for more info.
941 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
942 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
943 /// next hop knows the preimage to payment_hash they can claim an additional amount as
944 /// specified in the last hop in the route! Thus, you should probably do your own
945 /// payment_preimage tracking (which you should already be doing as they represent "proof of
946 /// payment") and prevent double-sends yourself.
948 /// May generate a SendHTLCs message event on success, which should be relayed.
950 /// Raises APIError::RoutError when invalid route or forward parameter
951 /// (cltv_delta, fee, node public key) is specified.
952 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
953 /// (including due to previous monitor update failure or new permanent monitor update failure).
954 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
955 /// relevant updates.
957 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
958 /// and you may wish to retry via a different route immediately.
959 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
960 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
961 /// the payment via a different route unless you intend to pay twice!
962 pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
963 if route.hops.len() < 1 || route.hops.len() > 20 {
964 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
966 let our_node_id = self.get_our_node_id();
967 for (idx, hop) in route.hops.iter().enumerate() {
968 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
969 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
973 let session_priv = self.keys_manager.get_session_key();
975 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
977 let onion_keys = secp_call!(onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
978 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
979 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height)?;
980 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
982 let _ = self.total_consistency_lock.read().unwrap();
984 let err: Result<(), _> = loop {
985 let mut channel_lock = self.channel_state.lock().unwrap();
987 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
988 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
989 Some(id) => id.clone(),
992 let channel_state = channel_lock.borrow_parts();
993 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
995 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
996 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
998 if !chan.get().is_live() {
999 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1001 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1002 route: route.clone(),
1003 session_priv: session_priv.clone(),
1004 first_hop_htlc_msat: htlc_msat,
1005 }, onion_packet), channel_state, chan)
1007 Some((update_add, commitment_signed, chan_monitor)) => {
1008 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1009 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1010 // Note that MonitorUpdateFailed here indicates (per function docs)
1011 // that we will resent the commitment update once we unfree monitor
1012 // updating, so we have to take special care that we don't return
1013 // something else in case we will resend later!
1014 return Err(APIError::MonitorUpdateFailed);
1017 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1018 node_id: route.hops.first().unwrap().pubkey,
1019 updates: msgs::CommitmentUpdate {
1020 update_add_htlcs: vec![update_add],
1021 update_fulfill_htlcs: Vec::new(),
1022 update_fail_htlcs: Vec::new(),
1023 update_fail_malformed_htlcs: Vec::new(),
1031 } else { unreachable!(); }
1035 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1036 Ok(_) => unreachable!(),
1038 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1040 log_error!(self, "Got bad keys: {}!", e.err);
1041 let mut channel_state = self.channel_state.lock().unwrap();
1042 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1043 node_id: route.hops.first().unwrap().pubkey,
1047 Err(APIError::ChannelUnavailable { err: e.err })
1052 /// Call this upon creation of a funding transaction for the given channel.
1054 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1055 /// or your counterparty can steal your funds!
1057 /// Panics if a funding transaction has already been provided for this channel.
1059 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1060 /// be trivially prevented by using unique funding transaction keys per-channel).
1061 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1062 let _ = self.total_consistency_lock.read().unwrap();
1064 let (chan, msg, chan_monitor) = {
1066 let mut channel_state = self.channel_state.lock().unwrap();
1067 match channel_state.by_id.remove(temporary_channel_id) {
1069 (chan.get_outbound_funding_created(funding_txo)
1070 .map_err(|e| if let ChannelError::Close(msg) = e {
1071 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1072 } else { unreachable!(); })
1078 match handle_error!(self, res, chan.get_their_node_id()) {
1079 Ok(funding_msg) => {
1080 (chan, funding_msg.0, funding_msg.1)
1083 log_error!(self, "Got bad signatures: {}!", e.err);
1084 let mut channel_state = self.channel_state.lock().unwrap();
1085 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1086 node_id: chan.get_their_node_id(),
1093 // Because we have exclusive ownership of the channel here we can release the channel_state
1094 // lock before add_update_monitor
1095 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1099 let mut channel_state = self.channel_state.lock().unwrap();
1100 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1101 node_id: chan.get_their_node_id(),
1104 match channel_state.by_id.entry(chan.channel_id()) {
1105 hash_map::Entry::Occupied(_) => {
1106 panic!("Generated duplicate funding txid?");
1108 hash_map::Entry::Vacant(e) => {
1114 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1115 if !chan.should_announce() { return None }
1117 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1119 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1121 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1122 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1124 Some(msgs::AnnouncementSignatures {
1125 channel_id: chan.channel_id(),
1126 short_channel_id: chan.get_short_channel_id().unwrap(),
1127 node_signature: our_node_sig,
1128 bitcoin_signature: our_bitcoin_sig,
1132 /// Processes HTLCs which are pending waiting on random forward delay.
1134 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1135 /// Will likely generate further events.
1136 pub fn process_pending_htlc_forwards(&self) {
1137 let _ = self.total_consistency_lock.read().unwrap();
1139 let mut new_events = Vec::new();
1140 let mut failed_forwards = Vec::new();
1142 let mut channel_state_lock = self.channel_state.lock().unwrap();
1143 let channel_state = channel_state_lock.borrow_parts();
1145 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1149 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1150 if short_chan_id != 0 {
1151 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1152 Some(chan_id) => chan_id.clone(),
1154 failed_forwards.reserve(pending_forwards.len());
1155 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1156 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1157 short_channel_id: prev_short_channel_id,
1158 htlc_id: prev_htlc_id,
1159 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1161 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1166 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1168 let mut add_htlc_msgs = Vec::new();
1169 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1170 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1171 short_channel_id: prev_short_channel_id,
1172 htlc_id: prev_htlc_id,
1173 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1175 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()) {
1177 let chan_update = self.get_channel_update(forward_chan).unwrap();
1178 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1183 Some(msg) => { add_htlc_msgs.push(msg); },
1185 // Nothing to do here...we're waiting on a remote
1186 // revoke_and_ack before we can add anymore HTLCs. The Channel
1187 // will automatically handle building the update_add_htlc and
1188 // commitment_signed messages when we can.
1189 // TODO: Do some kind of timer to set the channel as !is_live()
1190 // as we don't really want others relying on us relaying through
1191 // this channel currently :/.
1198 if !add_htlc_msgs.is_empty() {
1199 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1202 if let ChannelError::Ignore(_) = e {
1203 panic!("Stated return value requirements in send_commitment() were not met");
1205 //TODO: Handle...this is bad!
1209 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1212 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1213 node_id: forward_chan.get_their_node_id(),
1214 updates: msgs::CommitmentUpdate {
1215 update_add_htlcs: add_htlc_msgs,
1216 update_fulfill_htlcs: Vec::new(),
1217 update_fail_htlcs: Vec::new(),
1218 update_fail_malformed_htlcs: Vec::new(),
1220 commitment_signed: commitment_msg,
1225 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1226 let prev_hop_data = HTLCPreviousHopData {
1227 short_channel_id: prev_short_channel_id,
1228 htlc_id: prev_htlc_id,
1229 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1231 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1232 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1233 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1235 new_events.push(events::Event::PaymentReceived {
1236 payment_hash: forward_info.payment_hash,
1237 amt: forward_info.amt_to_forward,
1244 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1246 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1247 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() }),
1251 if new_events.is_empty() { return }
1252 let mut events = self.pending_events.lock().unwrap();
1253 events.append(&mut new_events);
1256 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1257 /// after a PaymentReceived event.
1258 /// expected_value is the value you expected the payment to be for (not the amount it actually
1259 /// was for from the PaymentReceived event).
1260 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, expected_value: u64) -> bool {
1261 let _ = self.total_consistency_lock.read().unwrap();
1263 let mut channel_state = Some(self.channel_state.lock().unwrap());
1264 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1265 if let Some(mut sources) = removed_source {
1266 for htlc_with_hash in sources.drain(..) {
1267 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1268 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1269 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1270 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(expected_value).to_vec() });
1276 /// Fails an HTLC backwards to the sender of it to us.
1277 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1278 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1279 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1280 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1281 /// still-available channels.
1282 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1284 HTLCSource::OutboundRoute { ref route, .. } => {
1285 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1286 mem::drop(channel_state_lock);
1287 match &onion_error {
1288 &HTLCFailReason::ErrorPacket { ref err } => {
1290 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1292 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1293 // TODO: If we decided to blame ourselves (or one of our channels) in
1294 // process_onion_failure we should close that channel as it implies our
1295 // next-hop is needlessly blaming us!
1296 if let Some(update) = channel_update {
1297 self.channel_state.lock().unwrap().pending_msg_events.push(
1298 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1303 self.pending_events.lock().unwrap().push(
1304 events::Event::PaymentFailed {
1305 payment_hash: payment_hash.clone(),
1306 rejected_by_dest: !payment_retryable,
1308 error_code: onion_error_code
1312 &HTLCFailReason::Reason {
1316 // we get a fail_malformed_htlc from the first hop
1317 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1318 // failures here, but that would be insufficient as Router::get_route
1319 // generally ignores its view of our own channels as we provide them via
1321 // TODO: For non-temporary failures, we really should be closing the
1322 // channel here as we apparently can't relay through them anyway.
1323 self.pending_events.lock().unwrap().push(
1324 events::Event::PaymentFailed {
1325 payment_hash: payment_hash.clone(),
1326 rejected_by_dest: route.hops.len() == 1,
1328 error_code: Some(*failure_code),
1334 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1335 let err_packet = match onion_error {
1336 HTLCFailReason::Reason { failure_code, data } => {
1337 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1338 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1339 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1341 HTLCFailReason::ErrorPacket { err } => {
1342 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1343 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1347 let channel_state = channel_state_lock.borrow_parts();
1349 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1350 Some(chan_id) => chan_id.clone(),
1354 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1355 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1356 Ok(Some((msg, commitment_msg, chan_monitor))) => {
1357 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1360 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1361 node_id: chan.get_their_node_id(),
1362 updates: msgs::CommitmentUpdate {
1363 update_add_htlcs: Vec::new(),
1364 update_fulfill_htlcs: Vec::new(),
1365 update_fail_htlcs: vec![msg],
1366 update_fail_malformed_htlcs: Vec::new(),
1368 commitment_signed: commitment_msg,
1374 //TODO: Do something with e?
1382 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1383 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1384 /// should probably kick the net layer to go send messages if this returns true!
1386 /// May panic if called except in response to a PaymentReceived event.
1387 pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1388 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1390 let _ = self.total_consistency_lock.read().unwrap();
1392 let mut channel_state = Some(self.channel_state.lock().unwrap());
1393 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1394 if let Some(mut sources) = removed_source {
1395 for htlc_with_hash in sources.drain(..) {
1396 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1397 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1402 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1404 HTLCSource::OutboundRoute { .. } => {
1405 mem::drop(channel_state_lock);
1406 let mut pending_events = self.pending_events.lock().unwrap();
1407 pending_events.push(events::Event::PaymentSent {
1411 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1412 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1413 let channel_state = channel_state_lock.borrow_parts();
1415 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1416 Some(chan_id) => chan_id.clone(),
1418 // TODO: There is probably a channel manager somewhere that needs to
1419 // learn the preimage as the channel already hit the chain and that's
1425 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1426 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1427 Ok((msgs, monitor_option)) => {
1428 if let Some(chan_monitor) = monitor_option {
1429 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1430 unimplemented!();// but def dont push the event...
1433 if let Some((msg, commitment_signed)) = msgs {
1434 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1435 node_id: chan.get_their_node_id(),
1436 updates: msgs::CommitmentUpdate {
1437 update_add_htlcs: Vec::new(),
1438 update_fulfill_htlcs: vec![msg],
1439 update_fail_htlcs: Vec::new(),
1440 update_fail_malformed_htlcs: Vec::new(),
1448 // TODO: There is probably a channel manager somewhere that needs to
1449 // learn the preimage as the channel may be about to hit the chain.
1450 //TODO: Do something with e?
1458 /// Gets the node_id held by this ChannelManager
1459 pub fn get_our_node_id(&self) -> PublicKey {
1460 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1463 /// Used to restore channels to normal operation after a
1464 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1466 pub fn test_restore_channel_monitor(&self) {
1467 let mut close_results = Vec::new();
1468 let mut htlc_forwards = Vec::new();
1469 let mut htlc_failures = Vec::new();
1470 let _ = self.total_consistency_lock.read().unwrap();
1473 let mut channel_lock = self.channel_state.lock().unwrap();
1474 let channel_state = channel_lock.borrow_parts();
1475 let short_to_id = channel_state.short_to_id;
1476 let pending_msg_events = channel_state.pending_msg_events;
1477 channel_state.by_id.retain(|_, channel| {
1478 if channel.is_awaiting_monitor_update() {
1479 let chan_monitor = channel.channel_monitor();
1480 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1482 ChannelMonitorUpdateErr::PermanentFailure => {
1483 // TODO: There may be some pending HTLCs that we intended to fail
1484 // backwards when a monitor update failed. We should make sure
1485 // knowledge of those gets moved into the appropriate in-memory
1486 // ChannelMonitor and they get failed backwards once we get
1487 // on-chain confirmations.
1488 // Note I think #198 addresses this, so once its merged a test
1489 // should be written.
1490 if let Some(short_id) = channel.get_short_channel_id() {
1491 short_to_id.remove(&short_id);
1493 close_results.push(channel.force_shutdown());
1494 if let Ok(update) = self.get_channel_update(&channel) {
1495 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1501 ChannelMonitorUpdateErr::TemporaryFailure => true,
1504 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1505 if !pending_forwards.is_empty() {
1506 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1508 htlc_failures.append(&mut pending_failures);
1510 macro_rules! handle_cs { () => {
1511 if let Some(update) = commitment_update {
1512 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1513 node_id: channel.get_their_node_id(),
1518 macro_rules! handle_raa { () => {
1519 if let Some(revoke_and_ack) = raa {
1520 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1521 node_id: channel.get_their_node_id(),
1522 msg: revoke_and_ack,
1527 RAACommitmentOrder::CommitmentFirst => {
1531 RAACommitmentOrder::RevokeAndACKFirst => {
1542 for failure in htlc_failures.drain(..) {
1543 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1545 self.forward_htlcs(&mut htlc_forwards[..]);
1547 for res in close_results.drain(..) {
1548 self.finish_force_close_channel(res);
1552 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1553 if msg.chain_hash != self.genesis_hash {
1554 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1557 let channel = Channel::new_from_req(&*self.fee_estimator, &self.keys_manager, their_node_id.clone(), msg, 0, Arc::clone(&self.logger), &self.default_configuration)
1558 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1559 let mut channel_state_lock = self.channel_state.lock().unwrap();
1560 let channel_state = channel_state_lock.borrow_parts();
1561 match channel_state.by_id.entry(channel.channel_id()) {
1562 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1563 hash_map::Entry::Vacant(entry) => {
1564 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1565 node_id: their_node_id.clone(),
1566 msg: channel.get_accept_channel(),
1568 entry.insert(channel);
1574 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1575 let (value, output_script, user_id) = {
1576 let mut channel_lock = self.channel_state.lock().unwrap();
1577 let channel_state = channel_lock.borrow_parts();
1578 match channel_state.by_id.entry(msg.temporary_channel_id) {
1579 hash_map::Entry::Occupied(mut chan) => {
1580 if chan.get().get_their_node_id() != *their_node_id {
1581 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1582 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1584 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1585 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1587 //TODO: same as above
1588 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1591 let mut pending_events = self.pending_events.lock().unwrap();
1592 pending_events.push(events::Event::FundingGenerationReady {
1593 temporary_channel_id: msg.temporary_channel_id,
1594 channel_value_satoshis: value,
1595 output_script: output_script,
1596 user_channel_id: user_id,
1601 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1602 let ((funding_msg, monitor_update), chan) = {
1603 let mut channel_lock = self.channel_state.lock().unwrap();
1604 let channel_state = channel_lock.borrow_parts();
1605 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1606 hash_map::Entry::Occupied(mut chan) => {
1607 if chan.get().get_their_node_id() != *their_node_id {
1608 //TODO: here and below MsgHandleErrInternal, #153 case
1609 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1611 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1613 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1616 // Because we have exclusive ownership of the channel here we can release the channel_state
1617 // lock before add_update_monitor
1618 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1621 let mut channel_state_lock = self.channel_state.lock().unwrap();
1622 let channel_state = channel_state_lock.borrow_parts();
1623 match channel_state.by_id.entry(funding_msg.channel_id) {
1624 hash_map::Entry::Occupied(_) => {
1625 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1627 hash_map::Entry::Vacant(e) => {
1628 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1629 node_id: their_node_id.clone(),
1638 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1639 let (funding_txo, user_id) = {
1640 let mut channel_lock = self.channel_state.lock().unwrap();
1641 let channel_state = channel_lock.borrow_parts();
1642 match channel_state.by_id.entry(msg.channel_id) {
1643 hash_map::Entry::Occupied(mut chan) => {
1644 if chan.get().get_their_node_id() != *their_node_id {
1645 //TODO: here and below MsgHandleErrInternal, #153 case
1646 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1648 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1649 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1652 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1654 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1657 let mut pending_events = self.pending_events.lock().unwrap();
1658 pending_events.push(events::Event::FundingBroadcastSafe {
1659 funding_txo: funding_txo,
1660 user_channel_id: user_id,
1665 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1666 let mut channel_state_lock = self.channel_state.lock().unwrap();
1667 let channel_state = channel_state_lock.borrow_parts();
1668 match channel_state.by_id.entry(msg.channel_id) {
1669 hash_map::Entry::Occupied(mut chan) => {
1670 if chan.get().get_their_node_id() != *their_node_id {
1671 //TODO: here and below MsgHandleErrInternal, #153 case
1672 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1674 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1675 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1676 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1677 node_id: their_node_id.clone(),
1678 msg: announcement_sigs,
1683 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1687 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1688 let (mut dropped_htlcs, chan_option) = {
1689 let mut channel_state_lock = self.channel_state.lock().unwrap();
1690 let channel_state = channel_state_lock.borrow_parts();
1692 match channel_state.by_id.entry(msg.channel_id.clone()) {
1693 hash_map::Entry::Occupied(mut chan_entry) => {
1694 if chan_entry.get().get_their_node_id() != *their_node_id {
1695 //TODO: here and below MsgHandleErrInternal, #153 case
1696 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1698 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1699 if let Some(msg) = shutdown {
1700 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1701 node_id: their_node_id.clone(),
1705 if let Some(msg) = closing_signed {
1706 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1707 node_id: their_node_id.clone(),
1711 if chan_entry.get().is_shutdown() {
1712 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1713 channel_state.short_to_id.remove(&short_id);
1715 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1716 } else { (dropped_htlcs, None) }
1718 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1721 for htlc_source in dropped_htlcs.drain(..) {
1722 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
1724 if let Some(chan) = chan_option {
1725 if let Ok(update) = self.get_channel_update(&chan) {
1726 let mut channel_state = self.channel_state.lock().unwrap();
1727 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1735 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1736 let (tx, chan_option) = {
1737 let mut channel_state_lock = self.channel_state.lock().unwrap();
1738 let channel_state = channel_state_lock.borrow_parts();
1739 match channel_state.by_id.entry(msg.channel_id.clone()) {
1740 hash_map::Entry::Occupied(mut chan_entry) => {
1741 if chan_entry.get().get_their_node_id() != *their_node_id {
1742 //TODO: here and below MsgHandleErrInternal, #153 case
1743 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1745 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1746 if let Some(msg) = closing_signed {
1747 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1748 node_id: their_node_id.clone(),
1753 // We're done with this channel, we've got a signed closing transaction and
1754 // will send the closing_signed back to the remote peer upon return. This
1755 // also implies there are no pending HTLCs left on the channel, so we can
1756 // fully delete it from tracking (the channel monitor is still around to
1757 // watch for old state broadcasts)!
1758 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1759 channel_state.short_to_id.remove(&short_id);
1761 (tx, Some(chan_entry.remove_entry().1))
1762 } else { (tx, None) }
1764 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1767 if let Some(broadcast_tx) = tx {
1768 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1770 if let Some(chan) = chan_option {
1771 if let Ok(update) = self.get_channel_update(&chan) {
1772 let mut channel_state = self.channel_state.lock().unwrap();
1773 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1781 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1782 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1783 //determine the state of the payment based on our response/if we forward anything/the time
1784 //we take to respond. We should take care to avoid allowing such an attack.
1786 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1787 //us repeatedly garbled in different ways, and compare our error messages, which are
1788 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1789 //but we should prevent it anyway.
1791 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1792 let channel_state = channel_state_lock.borrow_parts();
1794 match channel_state.by_id.entry(msg.channel_id) {
1795 hash_map::Entry::Occupied(mut chan) => {
1796 if chan.get().get_their_node_id() != *their_node_id {
1797 //TODO: here MsgHandleErrInternal, #153 case
1798 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1800 if !chan.get().is_usable() {
1801 // If the update_add is completely bogus, the call will Err and we will close,
1802 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
1803 // want to reject the new HTLC and fail it backwards instead of forwarding.
1804 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
1805 let chan_update = self.get_channel_update(chan.get());
1806 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1807 channel_id: msg.channel_id,
1808 htlc_id: msg.htlc_id,
1809 reason: if let Ok(update) = chan_update {
1810 // TODO: Note that |20 is defined as "channel FROM the processing
1811 // node has been disabled" (emphasis mine), which seems to imply
1812 // that we can't return |20 for an inbound channel being disabled.
1813 // This probably needs a spec update but should definitely be
1815 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
1816 let mut res = Vec::with_capacity(8 + 128);
1817 res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
1818 res.extend_from_slice(&update.encode_with_len()[..]);
1822 // This can only happen if the channel isn't in the fully-funded
1823 // state yet, implying our counterparty is trying to route payments
1824 // over the channel back to themselves (cause no one else should
1825 // know the short_id is a lightning channel yet). We should have no
1826 // problem just calling this unknown_next_peer
1827 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
1832 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
1834 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1839 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1840 let mut channel_lock = self.channel_state.lock().unwrap();
1842 let channel_state = channel_lock.borrow_parts();
1843 match channel_state.by_id.entry(msg.channel_id) {
1844 hash_map::Entry::Occupied(mut chan) => {
1845 if chan.get().get_their_node_id() != *their_node_id {
1846 //TODO: here and below MsgHandleErrInternal, #153 case
1847 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1849 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
1851 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1854 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
1858 // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
1859 // indicating that the payment itself failed
1860 fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
1861 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
1864 let mut htlc_msat = *first_hop_htlc_msat;
1865 let mut error_code_ret = None;
1866 let mut next_route_hop_ix = 0;
1867 let mut is_from_final_node = false;
1869 // Handle packed channel/node updates for passing back for the route handler
1870 onion_utils::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
1871 next_route_hop_ix += 1;
1872 if res.is_some() { return; }
1874 let amt_to_forward = htlc_msat - route_hop.fee_msat;
1875 htlc_msat = amt_to_forward;
1877 let ammag = onion_utils::gen_ammag_from_shared_secret(&shared_secret[..]);
1879 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1880 decryption_tmp.resize(packet_decrypted.len(), 0);
1881 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1882 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1883 packet_decrypted = decryption_tmp;
1885 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
1887 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
1888 let um = onion_utils::gen_um_from_shared_secret(&shared_secret[..]);
1889 let mut hmac = HmacEngine::<Sha256>::new(&um);
1890 hmac.input(&err_packet.encode()[32..]);
1892 if fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &err_packet.hmac) {
1893 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
1894 const PERM: u16 = 0x4000;
1895 const NODE: u16 = 0x2000;
1896 const UPDATE: u16 = 0x1000;
1898 let error_code = byte_utils::slice_to_be16(&error_code_slice);
1899 error_code_ret = Some(error_code);
1901 let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
1903 // indicate that payment parameter has failed and no need to
1904 // update Route object
1905 let payment_failed = (match error_code & 0xff {
1906 15|16|17|18|19 => true,
1908 } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
1909 || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
1911 let mut fail_channel_update = None;
1913 if error_code & NODE == NODE {
1914 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
1916 else if error_code & PERM == PERM {
1917 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1918 short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
1922 else if error_code & UPDATE == UPDATE {
1923 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
1924 let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
1925 if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
1926 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
1927 // if channel_update should NOT have caused the failure:
1928 // MAY treat the channel_update as invalid.
1929 let is_chan_update_invalid = match error_code & 0xff {
1931 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
1933 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) });
1934 new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
1936 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
1937 14 => false, // expiry_too_soon; always valid?
1938 20 => chan_update.contents.flags & 2 == 0,
1939 _ => false, // unknown error code; take channel_update as valid
1941 fail_channel_update = if is_chan_update_invalid {
1942 // This probably indicates the node which forwarded
1943 // to the node in question corrupted something.
1944 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1945 short_channel_id: route_hop.short_channel_id,
1949 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1956 if fail_channel_update.is_none() {
1957 // They provided an UPDATE which was obviously bogus, not worth
1958 // trying to relay through them anymore.
1959 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1960 node_id: route_hop.pubkey,
1964 } else if !payment_failed {
1965 // We can't understand their error messages and they failed to
1966 // forward...they probably can't understand our forwards so its
1967 // really not worth trying any further.
1968 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1969 node_id: route_hop.pubkey,
1974 // TODO: Here (and a few other places) we assume that BADONION errors
1975 // are always "sourced" from the node previous to the one which failed
1976 // to decode the onion.
1977 res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
1979 let (description, title) = errors::get_onion_error_description(error_code);
1980 if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
1981 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
1984 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
1987 // Useless packet that we can't use but it passed HMAC, so it
1988 // definitely came from the peer in question
1989 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
1990 node_id: route_hop.pubkey,
1992 }), !is_from_final_node));
1996 }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
1997 if let Some((channel_update, payment_retryable)) = res {
1998 (channel_update, payment_retryable, error_code_ret)
2000 // only not set either packet unparseable or hmac does not match with any
2001 // payment not retryable only when garbage is from the final node
2002 (None, !is_from_final_node, None)
2004 } else { unreachable!(); }
2007 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2008 let mut channel_lock = self.channel_state.lock().unwrap();
2009 let channel_state = channel_lock.borrow_parts();
2010 match channel_state.by_id.entry(msg.channel_id) {
2011 hash_map::Entry::Occupied(mut chan) => {
2012 if chan.get().get_their_node_id() != *their_node_id {
2013 //TODO: here and below MsgHandleErrInternal, #153 case
2014 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2016 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2018 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2023 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2024 let mut channel_lock = self.channel_state.lock().unwrap();
2025 let channel_state = channel_lock.borrow_parts();
2026 match channel_state.by_id.entry(msg.channel_id) {
2027 hash_map::Entry::Occupied(mut chan) => {
2028 if chan.get().get_their_node_id() != *their_node_id {
2029 //TODO: here and below MsgHandleErrInternal, #153 case
2030 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2032 if (msg.failure_code & 0x8000) == 0 {
2033 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2035 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }), channel_state, chan);
2038 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2042 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2043 let mut channel_state_lock = self.channel_state.lock().unwrap();
2044 let channel_state = channel_state_lock.borrow_parts();
2045 match channel_state.by_id.entry(msg.channel_id) {
2046 hash_map::Entry::Occupied(mut chan) => {
2047 if chan.get().get_their_node_id() != *their_node_id {
2048 //TODO: here and below MsgHandleErrInternal, #153 case
2049 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2051 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2052 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2053 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2054 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2055 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2057 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2058 node_id: their_node_id.clone(),
2059 msg: revoke_and_ack,
2061 if let Some(msg) = commitment_signed {
2062 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2063 node_id: their_node_id.clone(),
2064 updates: msgs::CommitmentUpdate {
2065 update_add_htlcs: Vec::new(),
2066 update_fulfill_htlcs: Vec::new(),
2067 update_fail_htlcs: Vec::new(),
2068 update_fail_malformed_htlcs: Vec::new(),
2070 commitment_signed: msg,
2074 if let Some(msg) = closing_signed {
2075 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2076 node_id: their_node_id.clone(),
2082 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2087 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2088 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2089 let mut forward_event = None;
2090 if !pending_forwards.is_empty() {
2091 let mut channel_state = self.channel_state.lock().unwrap();
2092 if channel_state.forward_htlcs.is_empty() {
2093 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));
2094 channel_state.next_forward = forward_event.unwrap();
2096 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2097 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2098 hash_map::Entry::Occupied(mut entry) => {
2099 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2101 hash_map::Entry::Vacant(entry) => {
2102 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2107 match forward_event {
2109 let mut pending_events = self.pending_events.lock().unwrap();
2110 pending_events.push(events::Event::PendingHTLCsForwardable {
2111 time_forwardable: time
2119 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2120 let (pending_forwards, mut pending_failures, short_channel_id) = {
2121 let mut channel_state_lock = self.channel_state.lock().unwrap();
2122 let channel_state = channel_state_lock.borrow_parts();
2123 match channel_state.by_id.entry(msg.channel_id) {
2124 hash_map::Entry::Occupied(mut chan) => {
2125 if chan.get().get_their_node_id() != *their_node_id {
2126 //TODO: here and below MsgHandleErrInternal, #153 case
2127 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2129 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2130 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2131 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2132 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2134 if let Some(updates) = commitment_update {
2135 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2136 node_id: their_node_id.clone(),
2140 if let Some(msg) = closing_signed {
2141 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2142 node_id: their_node_id.clone(),
2146 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2148 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2151 for failure in pending_failures.drain(..) {
2152 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2154 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2159 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2160 let mut channel_lock = self.channel_state.lock().unwrap();
2161 let channel_state = channel_lock.borrow_parts();
2162 match channel_state.by_id.entry(msg.channel_id) {
2163 hash_map::Entry::Occupied(mut chan) => {
2164 if chan.get().get_their_node_id() != *their_node_id {
2165 //TODO: here and below MsgHandleErrInternal, #153 case
2166 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2168 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2170 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2175 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2176 let mut channel_state_lock = self.channel_state.lock().unwrap();
2177 let channel_state = channel_state_lock.borrow_parts();
2179 match channel_state.by_id.entry(msg.channel_id) {
2180 hash_map::Entry::Occupied(mut chan) => {
2181 if chan.get().get_their_node_id() != *their_node_id {
2182 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2184 if !chan.get().is_usable() {
2185 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2188 let our_node_id = self.get_our_node_id();
2189 let (announcement, our_bitcoin_sig) =
2190 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2192 let were_node_one = announcement.node_id_1 == our_node_id;
2193 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2194 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2195 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2196 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2199 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2201 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2202 msg: msgs::ChannelAnnouncement {
2203 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2204 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2205 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2206 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2207 contents: announcement,
2209 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2212 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2217 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2218 let mut channel_state_lock = self.channel_state.lock().unwrap();
2219 let channel_state = channel_state_lock.borrow_parts();
2221 match channel_state.by_id.entry(msg.channel_id) {
2222 hash_map::Entry::Occupied(mut chan) => {
2223 if chan.get().get_their_node_id() != *their_node_id {
2224 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2226 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2227 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2228 if let Some(monitor) = channel_monitor {
2229 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2230 // channel_reestablish doesn't guarantee the order it returns is sensical
2231 // for the messages it returns, but if we're setting what messages to
2232 // re-transmit on monitor update success, we need to make sure it is sane.
2233 if revoke_and_ack.is_none() {
2234 order = RAACommitmentOrder::CommitmentFirst;
2236 if commitment_update.is_none() {
2237 order = RAACommitmentOrder::RevokeAndACKFirst;
2239 return_monitor_err!(self, e, channel_state, chan, order);
2240 //TODO: Resend the funding_locked if needed once we get the monitor running again
2243 if let Some(msg) = funding_locked {
2244 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2245 node_id: their_node_id.clone(),
2249 macro_rules! send_raa { () => {
2250 if let Some(msg) = revoke_and_ack {
2251 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2252 node_id: their_node_id.clone(),
2257 macro_rules! send_cu { () => {
2258 if let Some(updates) = commitment_update {
2259 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2260 node_id: their_node_id.clone(),
2266 RAACommitmentOrder::RevokeAndACKFirst => {
2270 RAACommitmentOrder::CommitmentFirst => {
2275 if let Some(msg) = shutdown {
2276 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2277 node_id: their_node_id.clone(),
2283 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2287 /// Begin Update fee process. Allowed only on an outbound channel.
2288 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2289 /// PeerManager::process_events afterwards.
2290 /// Note: This API is likely to change!
2292 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2293 let _ = self.total_consistency_lock.read().unwrap();
2295 let err: Result<(), _> = loop {
2296 let mut channel_state_lock = self.channel_state.lock().unwrap();
2297 let channel_state = channel_state_lock.borrow_parts();
2299 match channel_state.by_id.entry(channel_id) {
2300 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2301 hash_map::Entry::Occupied(mut chan) => {
2302 if !chan.get().is_outbound() {
2303 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2305 if chan.get().is_awaiting_monitor_update() {
2306 return Err(APIError::MonitorUpdateFailed);
2308 if !chan.get().is_live() {
2309 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2311 their_node_id = chan.get().get_their_node_id();
2312 if let Some((update_fee, commitment_signed, chan_monitor)) =
2313 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2315 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2318 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2319 node_id: chan.get().get_their_node_id(),
2320 updates: msgs::CommitmentUpdate {
2321 update_add_htlcs: Vec::new(),
2322 update_fulfill_htlcs: Vec::new(),
2323 update_fail_htlcs: Vec::new(),
2324 update_fail_malformed_htlcs: Vec::new(),
2325 update_fee: Some(update_fee),
2335 match handle_error!(self, err, their_node_id) {
2336 Ok(_) => unreachable!(),
2338 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2340 log_error!(self, "Got bad keys: {}!", e.err);
2341 let mut channel_state = self.channel_state.lock().unwrap();
2342 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2343 node_id: their_node_id,
2347 Err(APIError::APIMisuseError { err: e.err })
2353 impl events::MessageSendEventsProvider for ChannelManager {
2354 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2355 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2356 // user to serialize a ChannelManager with pending events in it and lose those events on
2357 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2359 //TODO: This behavior should be documented.
2360 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2361 if let Some(preimage) = htlc_update.payment_preimage {
2362 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2363 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2365 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2366 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2371 let mut ret = Vec::new();
2372 let mut channel_state = self.channel_state.lock().unwrap();
2373 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2378 impl events::EventsProvider for ChannelManager {
2379 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2380 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2381 // user to serialize a ChannelManager with pending events in it and lose those events on
2382 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2384 //TODO: This behavior should be documented.
2385 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2386 if let Some(preimage) = htlc_update.payment_preimage {
2387 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2388 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2390 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2391 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2396 let mut ret = Vec::new();
2397 let mut pending_events = self.pending_events.lock().unwrap();
2398 mem::swap(&mut ret, &mut *pending_events);
2403 impl ChainListener for ChannelManager {
2404 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2405 let header_hash = header.bitcoin_hash();
2406 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2407 let _ = self.total_consistency_lock.read().unwrap();
2408 let mut failed_channels = Vec::new();
2410 let mut channel_lock = self.channel_state.lock().unwrap();
2411 let channel_state = channel_lock.borrow_parts();
2412 let short_to_id = channel_state.short_to_id;
2413 let pending_msg_events = channel_state.pending_msg_events;
2414 channel_state.by_id.retain(|_, channel| {
2415 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2416 if let Ok(Some(funding_locked)) = chan_res {
2417 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2418 node_id: channel.get_their_node_id(),
2419 msg: funding_locked,
2421 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2422 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2423 node_id: channel.get_their_node_id(),
2424 msg: announcement_sigs,
2427 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2428 } else if let Err(e) = chan_res {
2429 pending_msg_events.push(events::MessageSendEvent::HandleError {
2430 node_id: channel.get_their_node_id(),
2431 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2435 if let Some(funding_txo) = channel.get_funding_txo() {
2436 for tx in txn_matched {
2437 for inp in tx.input.iter() {
2438 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2439 log_trace!(self, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
2440 if let Some(short_id) = channel.get_short_channel_id() {
2441 short_to_id.remove(&short_id);
2443 // It looks like our counterparty went on-chain. We go ahead and
2444 // broadcast our latest local state as well here, just in case its
2445 // some kind of SPV attack, though we expect these to be dropped.
2446 failed_channels.push(channel.force_shutdown());
2447 if let Ok(update) = self.get_channel_update(&channel) {
2448 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2457 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2458 if let Some(short_id) = channel.get_short_channel_id() {
2459 short_to_id.remove(&short_id);
2461 failed_channels.push(channel.force_shutdown());
2462 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2463 // the latest local tx for us, so we should skip that here (it doesn't really
2464 // hurt anything, but does make tests a bit simpler).
2465 failed_channels.last_mut().unwrap().0 = Vec::new();
2466 if let Ok(update) = self.get_channel_update(&channel) {
2467 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2476 for failure in failed_channels.drain(..) {
2477 self.finish_force_close_channel(failure);
2479 self.latest_block_height.store(height as usize, Ordering::Release);
2480 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2483 /// We force-close the channel without letting our counterparty participate in the shutdown
2484 fn block_disconnected(&self, header: &BlockHeader) {
2485 let _ = self.total_consistency_lock.read().unwrap();
2486 let mut failed_channels = Vec::new();
2488 let mut channel_lock = self.channel_state.lock().unwrap();
2489 let channel_state = channel_lock.borrow_parts();
2490 let short_to_id = channel_state.short_to_id;
2491 let pending_msg_events = channel_state.pending_msg_events;
2492 channel_state.by_id.retain(|_, v| {
2493 if v.block_disconnected(header) {
2494 if let Some(short_id) = v.get_short_channel_id() {
2495 short_to_id.remove(&short_id);
2497 failed_channels.push(v.force_shutdown());
2498 if let Ok(update) = self.get_channel_update(&v) {
2499 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2509 for failure in failed_channels.drain(..) {
2510 self.finish_force_close_channel(failure);
2512 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2513 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2517 impl ChannelMessageHandler for ChannelManager {
2518 //TODO: Handle errors and close channel (or so)
2519 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2520 let _ = self.total_consistency_lock.read().unwrap();
2521 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2524 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2525 let _ = self.total_consistency_lock.read().unwrap();
2526 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2529 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2530 let _ = self.total_consistency_lock.read().unwrap();
2531 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2534 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2535 let _ = self.total_consistency_lock.read().unwrap();
2536 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2539 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2540 let _ = self.total_consistency_lock.read().unwrap();
2541 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2544 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2545 let _ = self.total_consistency_lock.read().unwrap();
2546 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2549 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2550 let _ = self.total_consistency_lock.read().unwrap();
2551 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2554 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2555 let _ = self.total_consistency_lock.read().unwrap();
2556 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2559 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2560 let _ = self.total_consistency_lock.read().unwrap();
2561 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2564 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2565 let _ = self.total_consistency_lock.read().unwrap();
2566 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2569 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2570 let _ = self.total_consistency_lock.read().unwrap();
2571 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2574 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2575 let _ = self.total_consistency_lock.read().unwrap();
2576 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2579 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2580 let _ = self.total_consistency_lock.read().unwrap();
2581 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2584 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2585 let _ = self.total_consistency_lock.read().unwrap();
2586 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2589 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2590 let _ = self.total_consistency_lock.read().unwrap();
2591 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2594 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2595 let _ = self.total_consistency_lock.read().unwrap();
2596 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2599 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2600 let _ = self.total_consistency_lock.read().unwrap();
2601 let mut failed_channels = Vec::new();
2602 let mut failed_payments = Vec::new();
2604 let mut channel_state_lock = self.channel_state.lock().unwrap();
2605 let channel_state = channel_state_lock.borrow_parts();
2606 let short_to_id = channel_state.short_to_id;
2607 let pending_msg_events = channel_state.pending_msg_events;
2608 if no_connection_possible {
2609 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2610 channel_state.by_id.retain(|_, chan| {
2611 if chan.get_their_node_id() == *their_node_id {
2612 if let Some(short_id) = chan.get_short_channel_id() {
2613 short_to_id.remove(&short_id);
2615 failed_channels.push(chan.force_shutdown());
2616 if let Ok(update) = self.get_channel_update(&chan) {
2617 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2627 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2628 channel_state.by_id.retain(|_, chan| {
2629 if chan.get_their_node_id() == *their_node_id {
2630 //TODO: mark channel disabled (and maybe announce such after a timeout).
2631 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2632 if !failed_adds.is_empty() {
2633 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
2634 failed_payments.push((chan_update, failed_adds));
2636 if chan.is_shutdown() {
2637 if let Some(short_id) = chan.get_short_channel_id() {
2638 short_to_id.remove(&short_id);
2647 for failure in failed_channels.drain(..) {
2648 self.finish_force_close_channel(failure);
2650 for (chan_update, mut htlc_sources) in failed_payments {
2651 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2652 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2657 fn peer_connected(&self, their_node_id: &PublicKey) {
2658 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2660 let _ = self.total_consistency_lock.read().unwrap();
2661 let mut channel_state_lock = self.channel_state.lock().unwrap();
2662 let channel_state = channel_state_lock.borrow_parts();
2663 let pending_msg_events = channel_state.pending_msg_events;
2664 channel_state.by_id.retain(|_, chan| {
2665 if chan.get_their_node_id() == *their_node_id {
2666 if !chan.have_received_message() {
2667 // If we created this (outbound) channel while we were disconnected from the
2668 // peer we probably failed to send the open_channel message, which is now
2669 // lost. We can't have had anything pending related to this channel, so we just
2673 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2674 node_id: chan.get_their_node_id(),
2675 msg: chan.get_channel_reestablish(),
2681 //TODO: Also re-broadcast announcement_signatures
2684 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2685 let _ = self.total_consistency_lock.read().unwrap();
2687 if msg.channel_id == [0; 32] {
2688 for chan in self.list_channels() {
2689 if chan.remote_network_id == *their_node_id {
2690 self.force_close_channel(&chan.channel_id);
2694 self.force_close_channel(&msg.channel_id);
2699 const SERIALIZATION_VERSION: u8 = 1;
2700 const MIN_SERIALIZATION_VERSION: u8 = 1;
2702 impl Writeable for PendingForwardHTLCInfo {
2703 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2704 if let &Some(ref onion) = &self.onion_packet {
2706 onion.write(writer)?;
2710 self.incoming_shared_secret.write(writer)?;
2711 self.payment_hash.write(writer)?;
2712 self.short_channel_id.write(writer)?;
2713 self.amt_to_forward.write(writer)?;
2714 self.outgoing_cltv_value.write(writer)?;
2719 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2720 fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2721 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2723 1 => Some(msgs::OnionPacket::read(reader)?),
2724 _ => return Err(DecodeError::InvalidValue),
2726 Ok(PendingForwardHTLCInfo {
2728 incoming_shared_secret: Readable::read(reader)?,
2729 payment_hash: Readable::read(reader)?,
2730 short_channel_id: Readable::read(reader)?,
2731 amt_to_forward: Readable::read(reader)?,
2732 outgoing_cltv_value: Readable::read(reader)?,
2737 impl Writeable for HTLCFailureMsg {
2738 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2740 &HTLCFailureMsg::Relay(ref fail_msg) => {
2742 fail_msg.write(writer)?;
2744 &HTLCFailureMsg::Malformed(ref fail_msg) => {
2746 fail_msg.write(writer)?;
2753 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
2754 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
2755 match <u8 as Readable<R>>::read(reader)? {
2756 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
2757 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
2758 _ => Err(DecodeError::InvalidValue),
2763 impl Writeable for PendingHTLCStatus {
2764 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2766 &PendingHTLCStatus::Forward(ref forward_info) => {
2768 forward_info.write(writer)?;
2770 &PendingHTLCStatus::Fail(ref fail_msg) => {
2772 fail_msg.write(writer)?;
2779 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
2780 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
2781 match <u8 as Readable<R>>::read(reader)? {
2782 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
2783 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
2784 _ => Err(DecodeError::InvalidValue),
2789 impl_writeable!(HTLCPreviousHopData, 0, {
2792 incoming_packet_shared_secret
2795 impl Writeable for HTLCSource {
2796 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2798 &HTLCSource::PreviousHopData(ref hop_data) => {
2800 hop_data.write(writer)?;
2802 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
2804 route.write(writer)?;
2805 session_priv.write(writer)?;
2806 first_hop_htlc_msat.write(writer)?;
2813 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
2814 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
2815 match <u8 as Readable<R>>::read(reader)? {
2816 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
2817 1 => Ok(HTLCSource::OutboundRoute {
2818 route: Readable::read(reader)?,
2819 session_priv: Readable::read(reader)?,
2820 first_hop_htlc_msat: Readable::read(reader)?,
2822 _ => Err(DecodeError::InvalidValue),
2827 impl Writeable for HTLCFailReason {
2828 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2830 &HTLCFailReason::ErrorPacket { ref err } => {
2834 &HTLCFailReason::Reason { ref failure_code, ref data } => {
2836 failure_code.write(writer)?;
2837 data.write(writer)?;
2844 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
2845 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
2846 match <u8 as Readable<R>>::read(reader)? {
2847 0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
2848 1 => Ok(HTLCFailReason::Reason {
2849 failure_code: Readable::read(reader)?,
2850 data: Readable::read(reader)?,
2852 _ => Err(DecodeError::InvalidValue),
2857 impl_writeable!(HTLCForwardInfo, 0, {
2858 prev_short_channel_id,
2863 impl Writeable for ChannelManager {
2864 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2865 let _ = self.total_consistency_lock.write().unwrap();
2867 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
2868 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
2870 self.genesis_hash.write(writer)?;
2871 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
2872 self.last_block_hash.lock().unwrap().write(writer)?;
2874 let channel_state = self.channel_state.lock().unwrap();
2875 let mut unfunded_channels = 0;
2876 for (_, channel) in channel_state.by_id.iter() {
2877 if !channel.is_funding_initiated() {
2878 unfunded_channels += 1;
2881 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
2882 for (_, channel) in channel_state.by_id.iter() {
2883 if channel.is_funding_initiated() {
2884 channel.write(writer)?;
2888 (channel_state.forward_htlcs.len() as u64).write(writer)?;
2889 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
2890 short_channel_id.write(writer)?;
2891 (pending_forwards.len() as u64).write(writer)?;
2892 for forward in pending_forwards {
2893 forward.write(writer)?;
2897 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
2898 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
2899 payment_hash.write(writer)?;
2900 (previous_hops.len() as u64).write(writer)?;
2901 for previous_hop in previous_hops {
2902 previous_hop.write(writer)?;
2910 /// Arguments for the creation of a ChannelManager that are not deserialized.
2912 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
2914 /// 1) Deserialize all stored ChannelMonitors.
2915 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
2916 /// ChannelManager)>::read(reader, args).
2917 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
2918 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
2919 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
2920 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
2921 /// 4) Reconnect blocks on your ChannelMonitors.
2922 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
2923 /// 6) Disconnect/connect blocks on the ChannelManager.
2924 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
2925 /// automatically as it does in ChannelManager::new()).
2926 pub struct ChannelManagerReadArgs<'a> {
2927 /// The keys provider which will give us relevant keys. Some keys will be loaded during
2928 /// deserialization.
2929 pub keys_manager: Arc<KeysInterface>,
2931 /// The fee_estimator for use in the ChannelManager in the future.
2933 /// No calls to the FeeEstimator will be made during deserialization.
2934 pub fee_estimator: Arc<FeeEstimator>,
2935 /// The ManyChannelMonitor for use in the ChannelManager in the future.
2937 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
2938 /// you have deserialized ChannelMonitors separately and will add them to your
2939 /// ManyChannelMonitor after deserializing this ChannelManager.
2940 pub monitor: Arc<ManyChannelMonitor>,
2941 /// The ChainWatchInterface for use in the ChannelManager in the future.
2943 /// No calls to the ChainWatchInterface will be made during deserialization.
2944 pub chain_monitor: Arc<ChainWatchInterface>,
2945 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
2946 /// used to broadcast the latest local commitment transactions of channels which must be
2947 /// force-closed during deserialization.
2948 pub tx_broadcaster: Arc<BroadcasterInterface>,
2949 /// The Logger for use in the ChannelManager and which may be used to log information during
2950 /// deserialization.
2951 pub logger: Arc<Logger>,
2952 /// Default settings used for new channels. Any existing channels will continue to use the
2953 /// runtime settings which were stored when the ChannelManager was serialized.
2954 pub default_config: UserConfig,
2956 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
2957 /// value.get_funding_txo() should be the key).
2959 /// If a monitor is inconsistent with the channel state during deserialization the channel will
2960 /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
2961 /// is true for missing channels as well. If there is a monitor missing for which we find
2962 /// channel data Err(DecodeError::InvalidValue) will be returned.
2964 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
2966 pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
2969 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
2970 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
2971 let _ver: u8 = Readable::read(reader)?;
2972 let min_ver: u8 = Readable::read(reader)?;
2973 if min_ver > SERIALIZATION_VERSION {
2974 return Err(DecodeError::UnknownVersion);
2977 let genesis_hash: Sha256dHash = Readable::read(reader)?;
2978 let latest_block_height: u32 = Readable::read(reader)?;
2979 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2981 let mut closed_channels = Vec::new();
2983 let channel_count: u64 = Readable::read(reader)?;
2984 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
2985 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
2986 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
2987 for _ in 0..channel_count {
2988 let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
2989 if channel.last_block_connected != last_block_hash {
2990 return Err(DecodeError::InvalidValue);
2993 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
2994 funding_txo_set.insert(funding_txo.clone());
2995 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
2996 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
2997 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
2998 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
2999 let mut force_close_res = channel.force_shutdown();
3000 force_close_res.0 = monitor.get_latest_local_commitment_txn();
3001 closed_channels.push(force_close_res);
3003 if let Some(short_channel_id) = channel.get_short_channel_id() {
3004 short_to_id.insert(short_channel_id, channel.channel_id());
3006 by_id.insert(channel.channel_id(), channel);
3009 return Err(DecodeError::InvalidValue);
3013 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3014 if !funding_txo_set.contains(funding_txo) {
3015 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3019 let forward_htlcs_count: u64 = Readable::read(reader)?;
3020 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3021 for _ in 0..forward_htlcs_count {
3022 let short_channel_id = Readable::read(reader)?;
3023 let pending_forwards_count: u64 = Readable::read(reader)?;
3024 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3025 for _ in 0..pending_forwards_count {
3026 pending_forwards.push(Readable::read(reader)?);
3028 forward_htlcs.insert(short_channel_id, pending_forwards);
3031 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3032 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3033 for _ in 0..claimable_htlcs_count {
3034 let payment_hash = Readable::read(reader)?;
3035 let previous_hops_len: u64 = Readable::read(reader)?;
3036 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3037 for _ in 0..previous_hops_len {
3038 previous_hops.push(Readable::read(reader)?);
3040 claimable_htlcs.insert(payment_hash, previous_hops);
3043 let channel_manager = ChannelManager {
3045 fee_estimator: args.fee_estimator,
3046 monitor: args.monitor,
3047 chain_monitor: args.chain_monitor,
3048 tx_broadcaster: args.tx_broadcaster,
3050 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3051 last_block_hash: Mutex::new(last_block_hash),
3052 secp_ctx: Secp256k1::new(),
3054 channel_state: Mutex::new(ChannelHolder {
3057 next_forward: Instant::now(),
3060 pending_msg_events: Vec::new(),
3062 our_network_key: args.keys_manager.get_node_secret(),
3064 pending_events: Mutex::new(Vec::new()),
3065 total_consistency_lock: RwLock::new(()),
3066 keys_manager: args.keys_manager,
3067 logger: args.logger,
3068 default_configuration: args.default_config,
3071 for close_res in closed_channels.drain(..) {
3072 channel_manager.finish_force_close_channel(close_res);
3073 //TODO: Broadcast channel update for closed channels, but only after we've made a
3074 //connection or two.
3077 Ok((last_block_hash.clone(), channel_manager))
3083 use chain::chaininterface;
3084 use chain::transaction::OutPoint;
3085 use chain::chaininterface::{ChainListener, ChainWatchInterface};
3086 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3087 use chain::keysinterface;
3088 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3089 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3090 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3091 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3092 use ln::onion_utils;
3093 use ln::router::{Route, RouteHop, Router};
3095 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate};
3096 use util::test_utils;
3097 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3098 use util::errors::APIError;
3099 use util::logger::Logger;
3100 use util::ser::{Writeable, Writer, ReadableArgs};
3101 use util::config::UserConfig;
3103 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3104 use bitcoin::util::bip143;
3105 use bitcoin::util::address::Address;
3106 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3107 use bitcoin::blockdata::block::{Block, BlockHeader};
3108 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3109 use bitcoin::blockdata::script::{Builder, Script};
3110 use bitcoin::blockdata::opcodes;
3111 use bitcoin::blockdata::constants::genesis_block;
3112 use bitcoin::network::constants::Network;
3114 use bitcoin_hashes::sha256::Hash as Sha256;
3115 use bitcoin_hashes::Hash;
3117 use secp256k1::{Secp256k1, Message};
3118 use secp256k1::key::{PublicKey,SecretKey};
3120 use rand::{thread_rng,Rng};
3122 use std::cell::RefCell;
3123 use std::collections::{BTreeSet, HashMap, HashSet};
3124 use std::default::Default;
3126 use std::sync::{Arc, Mutex};
3127 use std::sync::atomic::Ordering;
3128 use std::time::Instant;
3131 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3132 assert!(chain.does_match_tx(tx));
3133 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3134 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3136 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3137 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3142 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3143 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3144 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3145 keys_manager: Arc<test_utils::TestKeysInterface>,
3146 node: Arc<ChannelManager>,
3148 node_seed: [u8; 32],
3149 network_payment_count: Rc<RefCell<u8>>,
3150 network_chan_count: Rc<RefCell<u32>>,
3152 impl Drop for Node {
3153 fn drop(&mut self) {
3154 if !::std::thread::panicking() {
3155 // Check that we processed all pending events
3156 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3157 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3158 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3163 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3164 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3167 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) {
3168 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3169 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3170 (announcement, as_update, bs_update, channel_id, tx)
3173 macro_rules! get_revoke_commit_msgs {
3174 ($node: expr, $node_id: expr) => {
3176 let events = $node.node.get_and_clear_pending_msg_events();
3177 assert_eq!(events.len(), 2);
3179 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3180 assert_eq!(*node_id, $node_id);
3183 _ => panic!("Unexpected event"),
3184 }, match events[1] {
3185 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3186 assert_eq!(*node_id, $node_id);
3187 assert!(updates.update_add_htlcs.is_empty());
3188 assert!(updates.update_fulfill_htlcs.is_empty());
3189 assert!(updates.update_fail_htlcs.is_empty());
3190 assert!(updates.update_fail_malformed_htlcs.is_empty());
3191 assert!(updates.update_fee.is_none());
3192 updates.commitment_signed.clone()
3194 _ => panic!("Unexpected event"),
3200 macro_rules! get_event_msg {
3201 ($node: expr, $event_type: path, $node_id: expr) => {
3203 let events = $node.node.get_and_clear_pending_msg_events();
3204 assert_eq!(events.len(), 1);
3206 $event_type { ref node_id, ref msg } => {
3207 assert_eq!(*node_id, $node_id);
3210 _ => panic!("Unexpected event"),
3216 macro_rules! get_htlc_update_msgs {
3217 ($node: expr, $node_id: expr) => {
3219 let events = $node.node.get_and_clear_pending_msg_events();
3220 assert_eq!(events.len(), 1);
3222 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3223 assert_eq!(*node_id, $node_id);
3226 _ => panic!("Unexpected event"),
3232 macro_rules! get_feerate {
3233 ($node: expr, $channel_id: expr) => {
3235 let chan_lock = $node.node.channel_state.lock().unwrap();
3236 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3243 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3244 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3245 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id())).unwrap();
3246 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id())).unwrap();
3248 let chan_id = *node_a.network_chan_count.borrow();
3252 let events_2 = node_a.node.get_and_clear_pending_events();
3253 assert_eq!(events_2.len(), 1);
3255 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3256 assert_eq!(*channel_value_satoshis, channel_value);
3257 assert_eq!(user_channel_id, 42);
3259 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3260 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3262 funding_output = OutPoint::new(tx.txid(), 0);
3264 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3265 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3266 assert_eq!(added_monitors.len(), 1);
3267 assert_eq!(added_monitors[0].0, funding_output);
3268 added_monitors.clear();
3270 _ => panic!("Unexpected event"),
3273 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id())).unwrap();
3275 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3276 assert_eq!(added_monitors.len(), 1);
3277 assert_eq!(added_monitors[0].0, funding_output);
3278 added_monitors.clear();
3281 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id())).unwrap();
3283 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3284 assert_eq!(added_monitors.len(), 1);
3285 assert_eq!(added_monitors[0].0, funding_output);
3286 added_monitors.clear();
3289 let events_4 = node_a.node.get_and_clear_pending_events();
3290 assert_eq!(events_4.len(), 1);
3292 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3293 assert_eq!(user_channel_id, 42);
3294 assert_eq!(*funding_txo, funding_output);
3296 _ => panic!("Unexpected event"),
3302 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3303 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3304 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingLocked, node_a.node.get_our_node_id())).unwrap();
3308 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3309 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3310 assert_eq!(events_6.len(), 2);
3311 ((match events_6[0] {
3312 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3313 channel_id = msg.channel_id.clone();
3314 assert_eq!(*node_id, node_b.node.get_our_node_id());
3317 _ => panic!("Unexpected event"),
3318 }, match events_6[1] {
3319 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3320 assert_eq!(*node_id, node_b.node.get_our_node_id());
3323 _ => panic!("Unexpected event"),
3327 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) {
3328 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3329 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3333 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) {
3334 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3335 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3336 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3338 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3339 assert_eq!(events_7.len(), 1);
3340 let (announcement, bs_update) = match events_7[0] {
3341 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3344 _ => panic!("Unexpected event"),
3347 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3348 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3349 assert_eq!(events_8.len(), 1);
3350 let as_update = match events_8[0] {
3351 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3352 assert!(*announcement == *msg);
3353 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
3354 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
3357 _ => panic!("Unexpected event"),
3360 *node_a.network_chan_count.borrow_mut() += 1;
3362 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3365 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3366 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3369 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) {
3370 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3372 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3373 node.router.handle_channel_update(&chan_announcement.1).unwrap();
3374 node.router.handle_channel_update(&chan_announcement.2).unwrap();
3376 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3379 macro_rules! check_spends {
3380 ($tx: expr, $spends_tx: expr) => {
3382 let mut funding_tx_map = HashMap::new();
3383 let spends_tx = $spends_tx;
3384 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3385 $tx.verify(&funding_tx_map).unwrap();
3390 macro_rules! get_closing_signed_broadcast {
3391 ($node: expr, $dest_pubkey: expr) => {
3393 let events = $node.get_and_clear_pending_msg_events();
3394 assert!(events.len() == 1 || events.len() == 2);
3395 (match events[events.len() - 1] {
3396 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3397 assert_eq!(msg.contents.flags & 2, 2);
3400 _ => panic!("Unexpected event"),
3401 }, if events.len() == 2 {
3403 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3404 assert_eq!(*node_id, $dest_pubkey);
3407 _ => panic!("Unexpected event"),
3414 fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
3415 let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) };
3416 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3419 node_a.close_channel(channel_id).unwrap();
3420 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3422 let events_1 = node_b.get_and_clear_pending_msg_events();
3423 assert!(events_1.len() >= 1);
3424 let shutdown_b = match events_1[0] {
3425 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3426 assert_eq!(node_id, &node_a.get_our_node_id());
3429 _ => panic!("Unexpected event"),
3432 let closing_signed_b = if !close_inbound_first {
3433 assert_eq!(events_1.len(), 1);
3436 Some(match events_1[1] {
3437 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3438 assert_eq!(node_id, &node_a.get_our_node_id());
3441 _ => panic!("Unexpected event"),
3445 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3446 let (as_update, bs_update) = if close_inbound_first {
3447 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3448 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3449 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3450 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3451 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3453 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3454 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3455 assert!(none_b.is_none());
3456 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3457 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3458 (as_update, bs_update)
3460 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3462 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3463 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3464 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3465 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3467 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3468 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3469 assert!(none_a.is_none());
3470 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3471 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3472 (as_update, bs_update)
3474 assert_eq!(tx_a, tx_b);
3475 check_spends!(tx_a, funding_tx);
3477 (as_update, bs_update, tx_a)
3482 msgs: Vec<msgs::UpdateAddHTLC>,
3483 commitment_msg: msgs::CommitmentSigned,
3486 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3487 assert!(updates.update_fulfill_htlcs.is_empty());
3488 assert!(updates.update_fail_htlcs.is_empty());
3489 assert!(updates.update_fail_malformed_htlcs.is_empty());
3490 assert!(updates.update_fee.is_none());
3491 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3494 fn from_event(event: MessageSendEvent) -> SendEvent {
3496 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3497 _ => panic!("Unexpected event type!"),
3501 fn from_node(node: &Node) -> SendEvent {
3502 let mut events = node.node.get_and_clear_pending_msg_events();
3503 assert_eq!(events.len(), 1);
3504 SendEvent::from_event(events.pop().unwrap())
3508 macro_rules! check_added_monitors {
3509 ($node: expr, $count: expr) => {
3511 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3512 assert_eq!(added_monitors.len(), $count);
3513 added_monitors.clear();
3518 macro_rules! commitment_signed_dance {
3519 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3521 check_added_monitors!($node_a, 0);
3522 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3523 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3524 check_added_monitors!($node_a, 1);
3525 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3528 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3530 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3531 check_added_monitors!($node_b, 0);
3532 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3533 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3534 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3535 check_added_monitors!($node_b, 1);
3536 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3537 let (bs_revoke_and_ack, extra_msg_option) = {
3538 let events = $node_b.node.get_and_clear_pending_msg_events();
3539 assert!(events.len() <= 2);
3541 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3542 assert_eq!(*node_id, $node_a.node.get_our_node_id());
3545 _ => panic!("Unexpected event"),
3546 }, events.get(1).map(|e| e.clone()))
3548 check_added_monitors!($node_b, 1);
3549 if $fail_backwards {
3550 assert!($node_a.node.get_and_clear_pending_events().is_empty());
3551 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3553 (extra_msg_option, bs_revoke_and_ack)
3556 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3558 check_added_monitors!($node_a, 0);
3559 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3560 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3561 check_added_monitors!($node_a, 1);
3562 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3563 assert!(extra_msg_option.is_none());
3567 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3569 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3570 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3572 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3573 if $fail_backwards {
3574 assert_eq!(added_monitors.len(), 2);
3575 assert!(added_monitors[0].0 != added_monitors[1].0);
3577 assert_eq!(added_monitors.len(), 1);
3579 added_monitors.clear();
3584 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
3586 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
3589 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3591 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
3592 if $fail_backwards {
3593 let channel_state = $node_a.node.channel_state.lock().unwrap();
3594 assert_eq!(channel_state.pending_msg_events.len(), 1);
3595 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
3596 assert_ne!(*node_id, $node_b.node.get_our_node_id());
3597 } else { panic!("Unexpected event"); }
3599 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3605 macro_rules! get_payment_preimage_hash {
3608 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
3609 *$node.network_payment_count.borrow_mut() += 1;
3610 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
3611 (payment_preimage, payment_hash)
3616 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
3617 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3619 let mut payment_event = {
3620 origin_node.node.send_payment(route, our_payment_hash).unwrap();
3621 check_added_monitors!(origin_node, 1);
3623 let mut events = origin_node.node.get_and_clear_pending_msg_events();
3624 assert_eq!(events.len(), 1);
3625 SendEvent::from_event(events.remove(0))
3627 let mut prev_node = origin_node;
3629 for (idx, &node) in expected_route.iter().enumerate() {
3630 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
3632 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3633 check_added_monitors!(node, 0);
3634 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
3636 let events_1 = node.node.get_and_clear_pending_events();
3637 assert_eq!(events_1.len(), 1);
3639 Event::PendingHTLCsForwardable { .. } => { },
3640 _ => panic!("Unexpected event"),
3643 node.node.channel_state.lock().unwrap().next_forward = Instant::now();
3644 node.node.process_pending_htlc_forwards();
3646 if idx == expected_route.len() - 1 {
3647 let events_2 = node.node.get_and_clear_pending_events();
3648 assert_eq!(events_2.len(), 1);
3650 Event::PaymentReceived { ref payment_hash, amt } => {
3651 assert_eq!(our_payment_hash, *payment_hash);
3652 assert_eq!(amt, recv_value);
3654 _ => panic!("Unexpected event"),
3657 let mut events_2 = node.node.get_and_clear_pending_msg_events();
3658 assert_eq!(events_2.len(), 1);
3659 check_added_monitors!(node, 1);
3660 payment_event = SendEvent::from_event(events_2.remove(0));
3661 assert_eq!(payment_event.msgs.len(), 1);
3667 (our_payment_preimage, our_payment_hash)
3670 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
3671 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
3672 check_added_monitors!(expected_route.last().unwrap(), 1);
3674 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
3675 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3676 macro_rules! get_next_msgs {
3679 let events = $node.node.get_and_clear_pending_msg_events();
3680 assert_eq!(events.len(), 1);
3682 MessageSendEvent::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 } } => {
3683 assert!(update_add_htlcs.is_empty());
3684 assert_eq!(update_fulfill_htlcs.len(), 1);
3685 assert!(update_fail_htlcs.is_empty());
3686 assert!(update_fail_malformed_htlcs.is_empty());
3687 assert!(update_fee.is_none());
3688 expected_next_node = node_id.clone();
3689 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
3691 _ => panic!("Unexpected event"),
3697 macro_rules! last_update_fulfill_dance {
3698 ($node: expr, $prev_node: expr) => {
3700 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3701 check_added_monitors!($node, 0);
3702 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
3703 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
3707 macro_rules! mid_update_fulfill_dance {
3708 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
3710 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3711 check_added_monitors!($node, 1);
3712 let new_next_msgs = if $new_msgs {
3713 get_next_msgs!($node)
3715 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
3718 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
3719 next_msgs = new_next_msgs;
3724 let mut prev_node = expected_route.last().unwrap();
3725 for (idx, node) in expected_route.iter().rev().enumerate() {
3726 assert_eq!(expected_next_node, node.node.get_our_node_id());
3727 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
3728 if next_msgs.is_some() {
3729 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
3730 } else if update_next_msgs {
3731 next_msgs = get_next_msgs!(node);
3733 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
3735 if !skip_last && idx == expected_route.len() - 1 {
3736 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3743 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
3744 let events = origin_node.node.get_and_clear_pending_events();
3745 assert_eq!(events.len(), 1);
3747 Event::PaymentSent { payment_preimage } => {
3748 assert_eq!(payment_preimage, our_payment_preimage);
3750 _ => panic!("Unexpected event"),
3755 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
3756 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
3759 const TEST_FINAL_CLTV: u32 = 32;
3761 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
3762 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();
3763 assert_eq!(route.hops.len(), expected_route.len());
3764 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3765 assert_eq!(hop.pubkey, node.node.get_our_node_id());
3768 send_along_route(origin_node, route, expected_route, recv_value)
3771 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
3772 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();
3773 assert_eq!(route.hops.len(), expected_route.len());
3774 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3775 assert_eq!(hop.pubkey, node.node.get_our_node_id());
3778 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3780 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
3782 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
3783 _ => panic!("Unknown error variants"),
3787 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
3788 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
3789 claim_payment(&origin, expected_route, our_payment_preimage);
3792 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
3793 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, 0));
3794 check_added_monitors!(expected_route.last().unwrap(), 1);
3796 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
3797 macro_rules! update_fail_dance {
3798 ($node: expr, $prev_node: expr, $last_node: expr) => {
3800 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3801 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
3806 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3807 let mut prev_node = expected_route.last().unwrap();
3808 for (idx, node) in expected_route.iter().rev().enumerate() {
3809 assert_eq!(expected_next_node, node.node.get_our_node_id());
3810 if next_msgs.is_some() {
3811 // We may be the "last node" for the purpose of the commitment dance if we're
3812 // skipping the last node (implying it is disconnected) and we're the
3813 // second-to-last node!
3814 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
3817 let events = node.node.get_and_clear_pending_msg_events();
3818 if !skip_last || idx != expected_route.len() - 1 {
3819 assert_eq!(events.len(), 1);
3821 MessageSendEvent::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 } } => {
3822 assert!(update_add_htlcs.is_empty());
3823 assert!(update_fulfill_htlcs.is_empty());
3824 assert_eq!(update_fail_htlcs.len(), 1);
3825 assert!(update_fail_malformed_htlcs.is_empty());
3826 assert!(update_fee.is_none());
3827 expected_next_node = node_id.clone();
3828 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
3830 _ => panic!("Unexpected event"),
3833 assert!(events.is_empty());
3835 if !skip_last && idx == expected_route.len() - 1 {
3836 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3843 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
3845 let events = origin_node.node.get_and_clear_pending_events();
3846 assert_eq!(events.len(), 1);
3848 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3849 assert_eq!(payment_hash, our_payment_hash);
3850 assert!(rejected_by_dest);
3852 _ => panic!("Unexpected event"),
3857 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
3858 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
3861 fn create_network(node_count: usize) -> Vec<Node> {
3862 let mut nodes = Vec::new();
3863 let mut rng = thread_rng();
3864 let secp_ctx = Secp256k1::new();
3866 let chan_count = Rc::new(RefCell::new(0));
3867 let payment_count = Rc::new(RefCell::new(0));
3869 for i in 0..node_count {
3870 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
3871 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
3872 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
3873 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
3874 let mut seed = [0; 32];
3875 rng.fill_bytes(&mut seed);
3876 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
3877 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
3878 let mut config = UserConfig::new();
3879 config.channel_options.announced_channel = true;
3880 config.channel_limits.force_announced_channel_preference = false;
3881 let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), config).unwrap();
3882 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
3883 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
3884 network_payment_count: payment_count.clone(),
3885 network_chan_count: chan_count.clone(),
3893 fn test_async_inbound_update_fee() {
3894 let mut nodes = create_network(2);
3895 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3896 let channel_id = chan.2;
3899 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3903 // send (1) commitment_signed -.
3904 // <- update_add_htlc/commitment_signed
3905 // send (2) RAA (awaiting remote revoke) -.
3906 // (1) commitment_signed is delivered ->
3907 // .- send (3) RAA (awaiting remote revoke)
3908 // (2) RAA is delivered ->
3909 // .- send (4) commitment_signed
3910 // <- (3) RAA is delivered
3911 // send (5) commitment_signed -.
3912 // <- (4) commitment_signed is delivered
3914 // (5) commitment_signed is delivered ->
3916 // (6) RAA is delivered ->
3918 // First nodes[0] generates an update_fee
3919 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
3920 check_added_monitors!(nodes[0], 1);
3922 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
3923 assert_eq!(events_0.len(), 1);
3924 let (update_msg, commitment_signed) = match events_0[0] { // (1)
3925 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3926 (update_fee.as_ref(), commitment_signed)
3928 _ => panic!("Unexpected event"),
3931 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3933 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3934 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3935 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();
3936 check_added_monitors!(nodes[1], 1);
3938 let payment_event = {
3939 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
3940 assert_eq!(events_1.len(), 1);
3941 SendEvent::from_event(events_1.remove(0))
3943 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3944 assert_eq!(payment_event.msgs.len(), 1);
3946 // ...now when the messages get delivered everyone should be happy
3947 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3948 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
3949 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3950 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
3951 check_added_monitors!(nodes[0], 1);
3953 // deliver(1), generate (3):
3954 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3955 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3956 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
3957 check_added_monitors!(nodes[1], 1);
3959 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
3960 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3961 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
3962 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
3963 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
3964 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
3965 assert!(bs_update.update_fee.is_none()); // (4)
3966 check_added_monitors!(nodes[1], 1);
3968 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
3969 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3970 assert!(as_update.update_add_htlcs.is_empty()); // (5)
3971 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
3972 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
3973 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
3974 assert!(as_update.update_fee.is_none()); // (5)
3975 check_added_monitors!(nodes[0], 1);
3977 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
3978 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3979 // only (6) so get_event_msg's assert(len == 1) passes
3980 check_added_monitors!(nodes[0], 1);
3982 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
3983 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3984 check_added_monitors!(nodes[1], 1);
3986 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
3987 check_added_monitors!(nodes[0], 1);
3989 let events_2 = nodes[0].node.get_and_clear_pending_events();
3990 assert_eq!(events_2.len(), 1);
3992 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
3993 _ => panic!("Unexpected event"),
3996 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
3997 check_added_monitors!(nodes[1], 1);
4001 fn test_update_fee_unordered_raa() {
4002 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4003 // crash in an earlier version of the update_fee patch)
4004 let mut nodes = create_network(2);
4005 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4006 let channel_id = chan.2;
4009 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4011 // First nodes[0] generates an update_fee
4012 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4013 check_added_monitors!(nodes[0], 1);
4015 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4016 assert_eq!(events_0.len(), 1);
4017 let update_msg = match events_0[0] { // (1)
4018 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4021 _ => panic!("Unexpected event"),
4024 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4026 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4027 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4028 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();
4029 check_added_monitors!(nodes[1], 1);
4031 let payment_event = {
4032 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4033 assert_eq!(events_1.len(), 1);
4034 SendEvent::from_event(events_1.remove(0))
4036 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4037 assert_eq!(payment_event.msgs.len(), 1);
4039 // ...now when the messages get delivered everyone should be happy
4040 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4041 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4042 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4043 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4044 check_added_monitors!(nodes[0], 1);
4046 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4047 check_added_monitors!(nodes[1], 1);
4049 // We can't continue, sadly, because our (1) now has a bogus signature
4053 fn test_multi_flight_update_fee() {
4054 let nodes = create_network(2);
4055 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4056 let channel_id = chan.2;
4059 // update_fee/commitment_signed ->
4060 // .- send (1) RAA and (2) commitment_signed
4061 // update_fee (never committed) ->
4062 // (3) update_fee ->
4063 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4064 // don't track which updates correspond to which revoke_and_ack responses so we're in
4065 // AwaitingRAA mode and will not generate the update_fee yet.
4066 // <- (1) RAA delivered
4067 // (3) is generated and send (4) CS -.
4068 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4069 // know the per_commitment_point to use for it.
4070 // <- (2) commitment_signed delivered
4071 // revoke_and_ack ->
4072 // B should send no response here
4073 // (4) commitment_signed delivered ->
4074 // <- RAA/commitment_signed delivered
4075 // revoke_and_ack ->
4077 // First nodes[0] generates an update_fee
4078 let initial_feerate = get_feerate!(nodes[0], channel_id);
4079 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4080 check_added_monitors!(nodes[0], 1);
4082 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4083 assert_eq!(events_0.len(), 1);
4084 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4085 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4086 (update_fee.as_ref().unwrap(), commitment_signed)
4088 _ => panic!("Unexpected event"),
4091 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4092 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4093 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4094 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4095 check_added_monitors!(nodes[1], 1);
4097 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4099 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4100 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4101 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4103 // Create the (3) update_fee message that nodes[0] will generate before it does...
4104 let mut update_msg_2 = msgs::UpdateFee {
4105 channel_id: update_msg_1.channel_id.clone(),
4106 feerate_per_kw: (initial_feerate + 30) as u32,
4109 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4111 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4113 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4115 // Deliver (1), generating (3) and (4)
4116 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4117 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4118 check_added_monitors!(nodes[0], 1);
4119 assert!(as_second_update.update_add_htlcs.is_empty());
4120 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4121 assert!(as_second_update.update_fail_htlcs.is_empty());
4122 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4123 // Check that the update_fee newly generated matches what we delivered:
4124 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4125 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4127 // Deliver (2) commitment_signed
4128 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4129 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4130 check_added_monitors!(nodes[0], 1);
4131 // No commitment_signed so get_event_msg's assert(len == 1) passes
4133 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4134 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4135 check_added_monitors!(nodes[1], 1);
4138 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4139 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4140 check_added_monitors!(nodes[1], 1);
4142 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4143 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4144 check_added_monitors!(nodes[0], 1);
4146 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4147 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4148 // No commitment_signed so get_event_msg's assert(len == 1) passes
4149 check_added_monitors!(nodes[0], 1);
4151 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4152 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4153 check_added_monitors!(nodes[1], 1);
4157 fn test_update_fee_vanilla() {
4158 let nodes = create_network(2);
4159 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4160 let channel_id = chan.2;
4162 let feerate = get_feerate!(nodes[0], channel_id);
4163 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4164 check_added_monitors!(nodes[0], 1);
4166 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4167 assert_eq!(events_0.len(), 1);
4168 let (update_msg, commitment_signed) = match events_0[0] {
4169 MessageSendEvent::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 } } => {
4170 (update_fee.as_ref(), commitment_signed)
4172 _ => panic!("Unexpected event"),
4174 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4176 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4177 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4178 check_added_monitors!(nodes[1], 1);
4180 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4181 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4182 check_added_monitors!(nodes[0], 1);
4184 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4185 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4186 // No commitment_signed so get_event_msg's assert(len == 1) passes
4187 check_added_monitors!(nodes[0], 1);
4189 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4190 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4191 check_added_monitors!(nodes[1], 1);
4195 fn test_update_fee_that_funder_cannot_afford() {
4196 let nodes = create_network(2);
4197 let channel_value = 1888;
4198 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4199 let channel_id = chan.2;
4202 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4203 check_added_monitors!(nodes[0], 1);
4204 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4206 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4208 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4210 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4211 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4213 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4214 let chan = chan_lock.by_id.get(&channel_id).unwrap();
4216 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4217 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4218 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4219 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4220 actual_fee = channel_value - actual_fee;
4221 assert_eq!(total_fee, actual_fee);
4224 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4225 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4226 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4227 check_added_monitors!(nodes[0], 1);
4229 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4231 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4233 //While producing the commitment_signed response after handling a received update_fee request the
4234 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4235 //Should produce and error.
4236 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4238 assert!(match err.err {
4239 "Funding remote cannot afford proposed new fee" => true,
4243 //clear the message we could not handle
4244 nodes[1].node.get_and_clear_pending_msg_events();
4248 fn test_update_fee_with_fundee_update_add_htlc() {
4249 let mut nodes = create_network(2);
4250 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4251 let channel_id = chan.2;
4254 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4256 let feerate = get_feerate!(nodes[0], channel_id);
4257 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4258 check_added_monitors!(nodes[0], 1);
4260 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4261 assert_eq!(events_0.len(), 1);
4262 let (update_msg, commitment_signed) = match events_0[0] {
4263 MessageSendEvent::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 } } => {
4264 (update_fee.as_ref(), commitment_signed)
4266 _ => panic!("Unexpected event"),
4268 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4269 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4270 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4271 check_added_monitors!(nodes[1], 1);
4273 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4275 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4277 // nothing happens since node[1] is in AwaitingRemoteRevoke
4278 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4280 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4281 assert_eq!(added_monitors.len(), 0);
4282 added_monitors.clear();
4284 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4285 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4286 // node[1] has nothing to do
4288 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4289 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4290 check_added_monitors!(nodes[0], 1);
4292 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4293 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4294 // No commitment_signed so get_event_msg's assert(len == 1) passes
4295 check_added_monitors!(nodes[0], 1);
4296 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4297 check_added_monitors!(nodes[1], 1);
4298 // AwaitingRemoteRevoke ends here
4300 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4301 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4302 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4303 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4304 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4305 assert_eq!(commitment_update.update_fee.is_none(), true);
4307 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4308 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4309 check_added_monitors!(nodes[0], 1);
4310 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4312 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4313 check_added_monitors!(nodes[1], 1);
4314 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4316 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4317 check_added_monitors!(nodes[1], 1);
4318 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4319 // No commitment_signed so get_event_msg's assert(len == 1) passes
4321 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4322 check_added_monitors!(nodes[0], 1);
4323 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4325 let events = nodes[0].node.get_and_clear_pending_events();
4326 assert_eq!(events.len(), 1);
4328 Event::PendingHTLCsForwardable { .. } => { },
4329 _ => panic!("Unexpected event"),
4331 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4332 nodes[0].node.process_pending_htlc_forwards();
4334 let events = nodes[0].node.get_and_clear_pending_events();
4335 assert_eq!(events.len(), 1);
4337 Event::PaymentReceived { .. } => { },
4338 _ => panic!("Unexpected event"),
4341 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4343 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4344 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4345 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4349 fn test_update_fee() {
4350 let nodes = create_network(2);
4351 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4352 let channel_id = chan.2;
4355 // (1) update_fee/commitment_signed ->
4356 // <- (2) revoke_and_ack
4357 // .- send (3) commitment_signed
4358 // (4) update_fee/commitment_signed ->
4359 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4360 // <- (3) commitment_signed delivered
4361 // send (6) revoke_and_ack -.
4362 // <- (5) deliver revoke_and_ack
4363 // (6) deliver revoke_and_ack ->
4364 // .- send (7) commitment_signed in response to (4)
4365 // <- (7) deliver commitment_signed
4366 // revoke_and_ack ->
4368 // Create and deliver (1)...
4369 let feerate = get_feerate!(nodes[0], channel_id);
4370 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4371 check_added_monitors!(nodes[0], 1);
4373 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4374 assert_eq!(events_0.len(), 1);
4375 let (update_msg, commitment_signed) = match events_0[0] {
4376 MessageSendEvent::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 } } => {
4377 (update_fee.as_ref(), commitment_signed)
4379 _ => panic!("Unexpected event"),
4381 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4383 // Generate (2) and (3):
4384 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4385 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4386 check_added_monitors!(nodes[1], 1);
4389 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4390 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4391 check_added_monitors!(nodes[0], 1);
4393 // Create and deliver (4)...
4394 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4395 check_added_monitors!(nodes[0], 1);
4396 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4397 assert_eq!(events_0.len(), 1);
4398 let (update_msg, commitment_signed) = match events_0[0] {
4399 MessageSendEvent::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 } } => {
4400 (update_fee.as_ref(), commitment_signed)
4402 _ => panic!("Unexpected event"),
4405 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4406 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4407 check_added_monitors!(nodes[1], 1);
4409 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4410 // No commitment_signed so get_event_msg's assert(len == 1) passes
4412 // Handle (3), creating (6):
4413 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4414 check_added_monitors!(nodes[0], 1);
4415 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4416 // No commitment_signed so get_event_msg's assert(len == 1) passes
4419 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4420 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4421 check_added_monitors!(nodes[0], 1);
4423 // Deliver (6), creating (7):
4424 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4425 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4426 assert!(commitment_update.update_add_htlcs.is_empty());
4427 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4428 assert!(commitment_update.update_fail_htlcs.is_empty());
4429 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4430 assert!(commitment_update.update_fee.is_none());
4431 check_added_monitors!(nodes[1], 1);
4434 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4435 check_added_monitors!(nodes[0], 1);
4436 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4437 // No commitment_signed so get_event_msg's assert(len == 1) passes
4439 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4440 check_added_monitors!(nodes[1], 1);
4441 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4443 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4444 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4445 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4449 fn pre_funding_lock_shutdown_test() {
4450 // Test sending a shutdown prior to funding_locked after funding generation
4451 let nodes = create_network(2);
4452 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4453 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4454 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4455 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4457 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4458 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4459 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4460 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4461 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4463 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4464 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4465 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4466 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4467 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4468 assert!(node_0_none.is_none());
4470 assert!(nodes[0].node.list_channels().is_empty());
4471 assert!(nodes[1].node.list_channels().is_empty());
4475 fn updates_shutdown_wait() {
4476 // Test sending a shutdown with outstanding updates pending
4477 let mut nodes = create_network(3);
4478 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4479 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4480 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4481 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4483 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4485 nodes[0].node.close_channel(&chan_1.2).unwrap();
4486 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4487 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4488 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4489 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4491 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4492 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4494 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4495 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4496 else { panic!("New sends should fail!") };
4497 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4498 else { panic!("New sends should fail!") };
4500 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4501 check_added_monitors!(nodes[2], 1);
4502 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4503 assert!(updates.update_add_htlcs.is_empty());
4504 assert!(updates.update_fail_htlcs.is_empty());
4505 assert!(updates.update_fail_malformed_htlcs.is_empty());
4506 assert!(updates.update_fee.is_none());
4507 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4508 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4509 check_added_monitors!(nodes[1], 1);
4510 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4511 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4513 assert!(updates_2.update_add_htlcs.is_empty());
4514 assert!(updates_2.update_fail_htlcs.is_empty());
4515 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4516 assert!(updates_2.update_fee.is_none());
4517 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4518 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4519 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4521 let events = nodes[0].node.get_and_clear_pending_events();
4522 assert_eq!(events.len(), 1);
4524 Event::PaymentSent { ref payment_preimage } => {
4525 assert_eq!(our_payment_preimage, *payment_preimage);
4527 _ => panic!("Unexpected event"),
4530 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4531 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4532 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4533 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4534 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4535 assert!(node_0_none.is_none());
4537 assert!(nodes[0].node.list_channels().is_empty());
4539 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4540 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4541 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4542 assert!(nodes[1].node.list_channels().is_empty());
4543 assert!(nodes[2].node.list_channels().is_empty());
4547 fn htlc_fail_async_shutdown() {
4548 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4549 let mut nodes = create_network(3);
4550 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4551 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4553 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4554 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4555 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4556 check_added_monitors!(nodes[0], 1);
4557 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4558 assert_eq!(updates.update_add_htlcs.len(), 1);
4559 assert!(updates.update_fulfill_htlcs.is_empty());
4560 assert!(updates.update_fail_htlcs.is_empty());
4561 assert!(updates.update_fail_malformed_htlcs.is_empty());
4562 assert!(updates.update_fee.is_none());
4564 nodes[1].node.close_channel(&chan_1.2).unwrap();
4565 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4566 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4567 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4569 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4570 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4571 check_added_monitors!(nodes[1], 1);
4572 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4573 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4575 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4576 assert!(updates_2.update_add_htlcs.is_empty());
4577 assert!(updates_2.update_fulfill_htlcs.is_empty());
4578 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4579 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4580 assert!(updates_2.update_fee.is_none());
4582 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
4583 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4585 let events = nodes[0].node.get_and_clear_pending_events();
4586 assert_eq!(events.len(), 1);
4588 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
4589 assert_eq!(our_payment_hash, *payment_hash);
4590 assert!(!rejected_by_dest);
4592 _ => panic!("Unexpected event"),
4595 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4596 assert_eq!(msg_events.len(), 2);
4597 let node_0_closing_signed = match msg_events[0] {
4598 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
4599 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4602 _ => panic!("Unexpected event"),
4604 match msg_events[1] {
4605 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
4606 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
4608 _ => panic!("Unexpected event"),
4611 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4612 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4613 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4614 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4615 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4616 assert!(node_0_none.is_none());
4618 assert!(nodes[0].node.list_channels().is_empty());
4620 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4621 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4622 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4623 assert!(nodes[1].node.list_channels().is_empty());
4624 assert!(nodes[2].node.list_channels().is_empty());
4627 fn do_test_shutdown_rebroadcast(recv_count: u8) {
4628 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
4629 // messages delivered prior to disconnect
4630 let nodes = create_network(3);
4631 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4632 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4634 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4636 nodes[1].node.close_channel(&chan_1.2).unwrap();
4637 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4639 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4640 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4642 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4646 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4647 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4649 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4650 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
4651 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4652 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4654 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
4655 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4656 assert!(node_1_shutdown == node_1_2nd_shutdown);
4658 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
4659 let node_0_2nd_shutdown = if recv_count > 0 {
4660 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4661 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
4664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4665 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
4666 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
4668 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
4670 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4671 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4673 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4674 check_added_monitors!(nodes[2], 1);
4675 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4676 assert!(updates.update_add_htlcs.is_empty());
4677 assert!(updates.update_fail_htlcs.is_empty());
4678 assert!(updates.update_fail_malformed_htlcs.is_empty());
4679 assert!(updates.update_fee.is_none());
4680 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4681 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4682 check_added_monitors!(nodes[1], 1);
4683 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4684 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4686 assert!(updates_2.update_add_htlcs.is_empty());
4687 assert!(updates_2.update_fail_htlcs.is_empty());
4688 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4689 assert!(updates_2.update_fee.is_none());
4690 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4691 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4692 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4694 let events = nodes[0].node.get_and_clear_pending_events();
4695 assert_eq!(events.len(), 1);
4697 Event::PaymentSent { ref payment_preimage } => {
4698 assert_eq!(our_payment_preimage, *payment_preimage);
4700 _ => panic!("Unexpected event"),
4703 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4705 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4706 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4707 assert!(node_1_closing_signed.is_some());
4710 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4711 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4713 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4714 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
4715 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4716 if recv_count == 0 {
4717 // If all closing_signeds weren't delivered we can just resume where we left off...
4718 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4720 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
4721 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4722 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
4724 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
4725 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4726 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
4728 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
4729 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4731 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
4732 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4733 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
4735 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
4736 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4737 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4738 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4739 assert!(node_0_none.is_none());
4741 // If one node, however, received + responded with an identical closing_signed we end
4742 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
4743 // There isn't really anything better we can do simply, but in the future we might
4744 // explore storing a set of recently-closed channels that got disconnected during
4745 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
4746 // give our counterparty enough time to (potentially) broadcast a cooperative closing
4748 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4750 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
4751 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
4752 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
4753 let msgs::ErrorMessage {ref channel_id, ..} = msg;
4754 assert_eq!(*channel_id, chan_1.2);
4755 } else { panic!("Needed SendErrorMessage close"); }
4757 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
4758 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
4759 // closing_signed so we do it ourselves
4760 let events = nodes[0].node.get_and_clear_pending_msg_events();
4761 assert_eq!(events.len(), 1);
4763 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
4764 assert_eq!(msg.contents.flags & 2, 2);
4766 _ => panic!("Unexpected event"),
4770 assert!(nodes[0].node.list_channels().is_empty());
4772 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4773 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4774 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4775 assert!(nodes[1].node.list_channels().is_empty());
4776 assert!(nodes[2].node.list_channels().is_empty());
4780 fn test_shutdown_rebroadcast() {
4781 do_test_shutdown_rebroadcast(0);
4782 do_test_shutdown_rebroadcast(1);
4783 do_test_shutdown_rebroadcast(2);
4787 fn fake_network_test() {
4788 // Simple test which builds a network of ChannelManagers, connects them to each other, and
4789 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
4790 let nodes = create_network(4);
4792 // Create some initial channels
4793 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4794 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4795 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4797 // Rebalance the network a bit by relaying one payment through all the channels...
4798 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
4799 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
4800 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
4801 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
4803 // Send some more payments
4804 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
4805 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
4806 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
4808 // Test failure packets
4809 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
4810 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
4812 // Add a new channel that skips 3
4813 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
4815 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
4816 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
4817 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
4818 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
4819 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
4820 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
4821 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
4823 // Do some rebalance loop payments, simultaneously
4824 let mut hops = Vec::with_capacity(3);
4825 hops.push(RouteHop {
4826 pubkey: nodes[2].node.get_our_node_id(),
4827 short_channel_id: chan_2.0.contents.short_channel_id,
4829 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
4831 hops.push(RouteHop {
4832 pubkey: nodes[3].node.get_our_node_id(),
4833 short_channel_id: chan_3.0.contents.short_channel_id,
4835 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
4837 hops.push(RouteHop {
4838 pubkey: nodes[1].node.get_our_node_id(),
4839 short_channel_id: chan_4.0.contents.short_channel_id,
4841 cltv_expiry_delta: TEST_FINAL_CLTV,
4843 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;
4844 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;
4845 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
4847 let mut hops = Vec::with_capacity(3);
4848 hops.push(RouteHop {
4849 pubkey: nodes[3].node.get_our_node_id(),
4850 short_channel_id: chan_4.0.contents.short_channel_id,
4852 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
4854 hops.push(RouteHop {
4855 pubkey: nodes[2].node.get_our_node_id(),
4856 short_channel_id: chan_3.0.contents.short_channel_id,
4858 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
4860 hops.push(RouteHop {
4861 pubkey: nodes[1].node.get_our_node_id(),
4862 short_channel_id: chan_2.0.contents.short_channel_id,
4864 cltv_expiry_delta: TEST_FINAL_CLTV,
4866 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;
4867 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;
4868 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
4870 // Claim the rebalances...
4871 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
4872 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
4874 // Add a duplicate new channel from 2 to 4
4875 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
4877 // Send some payments across both channels
4878 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
4879 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
4880 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
4882 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
4884 //TODO: Test that routes work again here as we've been notified that the channel is full
4886 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
4887 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
4888 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
4890 // Close down the channels...
4891 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
4892 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
4893 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
4894 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
4895 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
4899 fn duplicate_htlc_test() {
4900 // Test that we accept duplicate payment_hash HTLCs across the network and that
4901 // claiming/failing them are all separate and don't effect each other
4902 let mut nodes = create_network(6);
4904 // Create some initial channels to route via 3 to 4/5 from 0/1/2
4905 create_announced_chan_between_nodes(&nodes, 0, 3);
4906 create_announced_chan_between_nodes(&nodes, 1, 3);
4907 create_announced_chan_between_nodes(&nodes, 2, 3);
4908 create_announced_chan_between_nodes(&nodes, 3, 4);
4909 create_announced_chan_between_nodes(&nodes, 3, 5);
4911 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
4913 *nodes[0].network_payment_count.borrow_mut() -= 1;
4914 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
4916 *nodes[0].network_payment_count.borrow_mut() -= 1;
4917 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
4919 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
4920 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
4921 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
4924 #[derive(PartialEq)]
4925 enum HTLCType { NONE, TIMEOUT, SUCCESS }
4926 /// Tests that the given node has broadcast transactions for the given Channel
4928 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
4929 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
4930 /// broadcast and the revoked outputs were claimed.
4932 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
4933 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
4935 /// All broadcast transactions must be accounted for in one of the above three types of we'll
4937 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
4938 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4939 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
4941 let mut res = Vec::with_capacity(2);
4942 node_txn.retain(|tx| {
4943 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
4944 check_spends!(tx, chan.3.clone());
4945 if commitment_tx.is_none() {
4946 res.push(tx.clone());
4951 if let Some(explicit_tx) = commitment_tx {
4952 res.push(explicit_tx.clone());
4955 assert_eq!(res.len(), 1);
4957 if has_htlc_tx != HTLCType::NONE {
4958 node_txn.retain(|tx| {
4959 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
4960 check_spends!(tx, res[0].clone());
4961 if has_htlc_tx == HTLCType::TIMEOUT {
4962 assert!(tx.lock_time != 0);
4964 assert!(tx.lock_time == 0);
4966 res.push(tx.clone());
4970 assert!(res.len() == 2 || res.len() == 3);
4972 assert_eq!(res[1], res[2]);
4976 assert!(node_txn.is_empty());
4980 /// Tests that the given node has broadcast a claim transaction against the provided revoked
4981 /// HTLC transaction.
4982 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
4983 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4984 assert_eq!(node_txn.len(), 1);
4985 node_txn.retain(|tx| {
4986 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
4987 check_spends!(tx, revoked_tx.clone());
4991 assert!(node_txn.is_empty());
4994 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
4995 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
4997 assert!(node_txn.len() >= 1);
4998 assert_eq!(node_txn[0].input.len(), 1);
4999 let mut found_prev = false;
5001 for tx in prev_txn {
5002 if node_txn[0].input[0].previous_output.txid == tx.txid() {
5003 check_spends!(node_txn[0], tx.clone());
5004 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5005 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5011 assert!(found_prev);
5013 let mut res = Vec::new();
5014 mem::swap(&mut *node_txn, &mut res);
5018 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5019 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5020 assert_eq!(events_1.len(), 1);
5021 let as_update = match events_1[0] {
5022 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5025 _ => panic!("Unexpected event"),
5028 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5029 assert_eq!(events_2.len(), 1);
5030 let bs_update = match events_2[0] {
5031 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5034 _ => panic!("Unexpected event"),
5038 node.router.handle_channel_update(&as_update).unwrap();
5039 node.router.handle_channel_update(&bs_update).unwrap();
5043 macro_rules! expect_pending_htlcs_forwardable {
5045 let events = $node.node.get_and_clear_pending_events();
5046 assert_eq!(events.len(), 1);
5048 Event::PendingHTLCsForwardable { .. } => { },
5049 _ => panic!("Unexpected event"),
5051 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5052 $node.node.process_pending_htlc_forwards();
5056 fn do_channel_reserve_test(test_recv: bool) {
5058 use std::sync::atomic::Ordering;
5059 use ln::msgs::HandleError;
5061 macro_rules! get_channel_value_stat {
5062 ($node: expr, $channel_id: expr) => {{
5063 let chan_lock = $node.node.channel_state.lock().unwrap();
5064 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5065 chan.get_value_stat()
5069 let mut nodes = create_network(3);
5070 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5071 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5073 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5074 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5076 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5077 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5079 macro_rules! get_route_and_payment_hash {
5080 ($recv_value: expr) => {{
5081 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5082 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5083 (route, payment_hash, payment_preimage)
5087 macro_rules! expect_forward {
5089 let mut events = $node.node.get_and_clear_pending_msg_events();
5090 assert_eq!(events.len(), 1);
5091 check_added_monitors!($node, 1);
5092 let payment_event = SendEvent::from_event(events.remove(0));
5097 macro_rules! expect_payment_received {
5098 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5099 let events = $node.node.get_and_clear_pending_events();
5100 assert_eq!(events.len(), 1);
5102 Event::PaymentReceived { ref payment_hash, amt } => {
5103 assert_eq!($expected_payment_hash, *payment_hash);
5104 assert_eq!($expected_recv_value, amt);
5106 _ => panic!("Unexpected event"),
5111 let feemsat = 239; // somehow we know?
5112 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5114 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5116 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5118 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5119 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5120 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5122 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5123 _ => panic!("Unknown error variants"),
5127 let mut htlc_id = 0;
5128 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5129 // nodes[0]'s wealth
5131 let amt_msat = recv_value_0 + total_fee_msat;
5132 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5135 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5138 let (stat01_, stat11_, stat12_, stat22_) = (
5139 get_channel_value_stat!(nodes[0], chan_1.2),
5140 get_channel_value_stat!(nodes[1], chan_1.2),
5141 get_channel_value_stat!(nodes[1], chan_2.2),
5142 get_channel_value_stat!(nodes[2], chan_2.2),
5145 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5146 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5147 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5148 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5149 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5153 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5154 // attempt to get channel_reserve violation
5155 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5156 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5158 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5159 _ => panic!("Unknown error variants"),
5163 // adding pending output
5164 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5165 let amt_msat_1 = recv_value_1 + total_fee_msat;
5167 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5168 let payment_event_1 = {
5169 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5170 check_added_monitors!(nodes[0], 1);
5172 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5173 assert_eq!(events.len(), 1);
5174 SendEvent::from_event(events.remove(0))
5176 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5178 // channel reserve test with htlc pending output > 0
5179 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5181 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5182 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5183 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5184 _ => panic!("Unknown error variants"),
5189 // test channel_reserve test on nodes[1] side
5190 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5192 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5193 let secp_ctx = Secp256k1::new();
5194 let session_priv = SecretKey::from_slice(&secp_ctx, &{
5195 let mut session_key = [0; 32];
5196 rng::fill_bytes(&mut session_key);
5198 }).expect("RNG is bad!");
5200 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5201 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5202 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5203 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5204 let msg = msgs::UpdateAddHTLC {
5205 channel_id: chan_1.2,
5207 amount_msat: htlc_msat,
5208 payment_hash: our_payment_hash,
5209 cltv_expiry: htlc_cltv,
5210 onion_routing_packet: onion_packet,
5214 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5216 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5218 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5219 assert_eq!(nodes[1].node.list_channels().len(), 1);
5220 assert_eq!(nodes[1].node.list_channels().len(), 1);
5221 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5222 assert_eq!(channel_close_broadcast.len(), 1);
5223 match channel_close_broadcast[0] {
5224 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5225 assert_eq!(msg.contents.flags & 2, 2);
5227 _ => panic!("Unexpected event"),
5233 // split the rest to test holding cell
5234 let recv_value_21 = recv_value_2/2;
5235 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5237 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5238 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);
5241 // now see if they go through on both sides
5242 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5243 // but this will stuck in the holding cell
5244 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5245 check_added_monitors!(nodes[0], 0);
5246 let events = nodes[0].node.get_and_clear_pending_events();
5247 assert_eq!(events.len(), 0);
5249 // test with outbound holding cell amount > 0
5251 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5252 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5253 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5254 _ => panic!("Unknown error variants"),
5258 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5259 // this will also stuck in the holding cell
5260 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5261 check_added_monitors!(nodes[0], 0);
5262 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5263 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5265 // flush the pending htlc
5266 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5267 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5268 check_added_monitors!(nodes[1], 1);
5270 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5271 check_added_monitors!(nodes[0], 1);
5272 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5274 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5275 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5276 // No commitment_signed so get_event_msg's assert(len == 1) passes
5277 check_added_monitors!(nodes[0], 1);
5279 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5280 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5281 check_added_monitors!(nodes[1], 1);
5283 expect_pending_htlcs_forwardable!(nodes[1]);
5285 let ref payment_event_11 = expect_forward!(nodes[1]);
5286 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5287 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5289 expect_pending_htlcs_forwardable!(nodes[2]);
5290 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5292 // flush the htlcs in the holding cell
5293 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5294 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5295 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5296 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5297 expect_pending_htlcs_forwardable!(nodes[1]);
5299 let ref payment_event_3 = expect_forward!(nodes[1]);
5300 assert_eq!(payment_event_3.msgs.len(), 2);
5301 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5302 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5304 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5305 expect_pending_htlcs_forwardable!(nodes[2]);
5307 let events = nodes[2].node.get_and_clear_pending_events();
5308 assert_eq!(events.len(), 2);
5310 Event::PaymentReceived { ref payment_hash, amt } => {
5311 assert_eq!(our_payment_hash_21, *payment_hash);
5312 assert_eq!(recv_value_21, amt);
5314 _ => panic!("Unexpected event"),
5317 Event::PaymentReceived { ref payment_hash, amt } => {
5318 assert_eq!(our_payment_hash_22, *payment_hash);
5319 assert_eq!(recv_value_22, amt);
5321 _ => panic!("Unexpected event"),
5324 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5325 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5326 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5328 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);
5329 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5330 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5331 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5333 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5334 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5338 fn channel_reserve_test() {
5339 do_channel_reserve_test(false);
5340 do_channel_reserve_test(true);
5344 fn channel_monitor_network_test() {
5345 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5346 // tests that ChannelMonitor is able to recover from various states.
5347 let nodes = create_network(5);
5349 // Create some initial channels
5350 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5351 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5352 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5353 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5355 // Rebalance the network a bit by relaying one payment through all the channels...
5356 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5357 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5358 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5359 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5361 // Simple case with no pending HTLCs:
5362 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5364 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5365 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5366 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5367 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5369 get_announce_close_broadcast_events(&nodes, 0, 1);
5370 assert_eq!(nodes[0].node.list_channels().len(), 0);
5371 assert_eq!(nodes[1].node.list_channels().len(), 1);
5373 // One pending HTLC is discarded by the force-close:
5374 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5376 // Simple case of one pending HTLC to HTLC-Timeout
5377 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5379 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5380 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5381 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5382 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5384 get_announce_close_broadcast_events(&nodes, 1, 2);
5385 assert_eq!(nodes[1].node.list_channels().len(), 0);
5386 assert_eq!(nodes[2].node.list_channels().len(), 1);
5388 macro_rules! claim_funds {
5389 ($node: expr, $prev_node: expr, $preimage: expr) => {
5391 assert!($node.node.claim_funds($preimage));
5392 check_added_monitors!($node, 1);
5394 let events = $node.node.get_and_clear_pending_msg_events();
5395 assert_eq!(events.len(), 1);
5397 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5398 assert!(update_add_htlcs.is_empty());
5399 assert!(update_fail_htlcs.is_empty());
5400 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5402 _ => panic!("Unexpected event"),
5408 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5409 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5410 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5412 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5414 // Claim the payment on nodes[3], giving it knowledge of the preimage
5415 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5417 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5418 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5420 check_preimage_claim(&nodes[3], &node_txn);
5422 get_announce_close_broadcast_events(&nodes, 2, 3);
5423 assert_eq!(nodes[2].node.list_channels().len(), 0);
5424 assert_eq!(nodes[3].node.list_channels().len(), 1);
5426 { // Cheat and reset nodes[4]'s height to 1
5427 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5428 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5431 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5432 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5433 // One pending HTLC to time out:
5434 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5435 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5439 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5440 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5441 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5442 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5443 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5446 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5448 // Claim the payment on nodes[4], giving it knowledge of the preimage
5449 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5451 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5452 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5453 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5454 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5455 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5458 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5460 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5461 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5463 check_preimage_claim(&nodes[4], &node_txn);
5465 get_announce_close_broadcast_events(&nodes, 3, 4);
5466 assert_eq!(nodes[3].node.list_channels().len(), 0);
5467 assert_eq!(nodes[4].node.list_channels().len(), 0);
5471 fn test_justice_tx() {
5472 // Test justice txn built on revoked HTLC-Success tx, against both sides
5474 let nodes = create_network(2);
5475 // Create some new channels:
5476 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5478 // A pending HTLC which will be revoked:
5479 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5480 // Get the will-be-revoked local txn from nodes[0]
5481 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5482 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5483 assert_eq!(revoked_local_txn[0].input.len(), 1);
5484 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5485 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5486 assert_eq!(revoked_local_txn[1].input.len(), 1);
5487 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5488 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5489 // Revoke the old state
5490 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5493 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5494 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5496 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5497 assert_eq!(node_txn.len(), 3);
5498 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5499 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5501 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5502 node_txn.swap_remove(0);
5504 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5506 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5507 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5508 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5509 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5510 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5512 get_announce_close_broadcast_events(&nodes, 0, 1);
5514 assert_eq!(nodes[0].node.list_channels().len(), 0);
5515 assert_eq!(nodes[1].node.list_channels().len(), 0);
5517 // We test justice_tx build by A on B's revoked HTLC-Success tx
5518 // Create some new channels:
5519 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5521 // A pending HTLC which will be revoked:
5522 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5523 // Get the will-be-revoked local txn from B
5524 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5525 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5526 assert_eq!(revoked_local_txn[0].input.len(), 1);
5527 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5528 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5529 // Revoke the old state
5530 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5532 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5533 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5535 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5536 assert_eq!(node_txn.len(), 3);
5537 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5538 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5540 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5541 node_txn.swap_remove(0);
5543 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5545 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5546 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5547 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5548 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5549 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5551 get_announce_close_broadcast_events(&nodes, 0, 1);
5552 assert_eq!(nodes[0].node.list_channels().len(), 0);
5553 assert_eq!(nodes[1].node.list_channels().len(), 0);
5557 fn revoked_output_claim() {
5558 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5559 // transaction is broadcast by its counterparty
5560 let nodes = create_network(2);
5561 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5562 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5563 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5564 assert_eq!(revoked_local_txn.len(), 1);
5565 // Only output is the full channel value back to nodes[0]:
5566 assert_eq!(revoked_local_txn[0].output.len(), 1);
5567 // Send a payment through, updating everyone's latest commitment txn
5568 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5570 // Inform nodes[1] that nodes[0] broadcast a stale tx
5571 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5572 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5573 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5574 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5576 assert_eq!(node_txn[0], node_txn[2]);
5578 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5579 check_spends!(node_txn[1], chan_1.3.clone());
5581 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5582 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5583 get_announce_close_broadcast_events(&nodes, 0, 1);
5587 fn claim_htlc_outputs_shared_tx() {
5588 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5589 let nodes = create_network(2);
5591 // Create some new channel:
5592 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5594 // Rebalance the network to generate htlc in the two directions
5595 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5596 // 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
5597 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5598 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
5600 // Get the will-be-revoked local txn from node[0]
5601 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5602 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
5603 assert_eq!(revoked_local_txn[0].input.len(), 1);
5604 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5605 assert_eq!(revoked_local_txn[1].input.len(), 1);
5606 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5607 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5608 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
5610 //Revoke the old state
5611 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
5614 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5615 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5616 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5618 let events = nodes[1].node.get_and_clear_pending_events();
5619 assert_eq!(events.len(), 1);
5621 Event::PaymentFailed { payment_hash, .. } => {
5622 assert_eq!(payment_hash, payment_hash_2);
5624 _ => panic!("Unexpected event"),
5627 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5628 assert_eq!(node_txn.len(), 4);
5630 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
5631 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5633 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
5635 let mut witness_lens = BTreeSet::new();
5636 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
5637 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
5638 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
5639 assert_eq!(witness_lens.len(), 3);
5640 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
5641 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
5642 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
5644 // Next nodes[1] broadcasts its current local tx state:
5645 assert_eq!(node_txn[1].input.len(), 1);
5646 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
5648 assert_eq!(node_txn[2].input.len(), 1);
5649 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
5650 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
5651 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
5652 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
5653 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
5655 get_announce_close_broadcast_events(&nodes, 0, 1);
5656 assert_eq!(nodes[0].node.list_channels().len(), 0);
5657 assert_eq!(nodes[1].node.list_channels().len(), 0);
5661 fn claim_htlc_outputs_single_tx() {
5662 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
5663 let nodes = create_network(2);
5665 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5667 // Rebalance the network to generate htlc in the two directions
5668 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5669 // 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
5670 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
5671 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5672 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
5674 // Get the will-be-revoked local txn from node[0]
5675 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5677 //Revoke the old state
5678 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
5681 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5682 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
5683 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
5685 let events = nodes[1].node.get_and_clear_pending_events();
5686 assert_eq!(events.len(), 1);
5688 Event::PaymentFailed { payment_hash, .. } => {
5689 assert_eq!(payment_hash, payment_hash_2);
5691 _ => panic!("Unexpected event"),
5694 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5695 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)
5697 assert_eq!(node_txn[0], node_txn[7]);
5698 assert_eq!(node_txn[1], node_txn[8]);
5699 assert_eq!(node_txn[2], node_txn[9]);
5700 assert_eq!(node_txn[3], node_txn[10]);
5701 assert_eq!(node_txn[4], node_txn[11]);
5702 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
5703 assert_eq!(node_txn[4], node_txn[6]);
5705 assert_eq!(node_txn[0].input.len(), 1);
5706 assert_eq!(node_txn[1].input.len(), 1);
5707 assert_eq!(node_txn[2].input.len(), 1);
5709 let mut revoked_tx_map = HashMap::new();
5710 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
5711 node_txn[0].verify(&revoked_tx_map).unwrap();
5712 node_txn[1].verify(&revoked_tx_map).unwrap();
5713 node_txn[2].verify(&revoked_tx_map).unwrap();
5715 let mut witness_lens = BTreeSet::new();
5716 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
5717 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
5718 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
5719 assert_eq!(witness_lens.len(), 3);
5720 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
5721 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
5722 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
5724 assert_eq!(node_txn[3].input.len(), 1);
5725 check_spends!(node_txn[3], chan_1.3.clone());
5727 assert_eq!(node_txn[4].input.len(), 1);
5728 let witness_script = node_txn[4].input[0].witness.last().unwrap();
5729 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
5730 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
5731 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
5732 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
5734 get_announce_close_broadcast_events(&nodes, 0, 1);
5735 assert_eq!(nodes[0].node.list_channels().len(), 0);
5736 assert_eq!(nodes[1].node.list_channels().len(), 0);
5740 fn test_htlc_on_chain_success() {
5741 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
5742 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
5743 // broadcasting the right event to other nodes in payment path.
5744 // A --------------------> B ----------------------> C (preimage)
5745 // First, C should claim the HTLC output via HTLC-Success when its own latest local
5746 // commitment transaction was broadcast.
5747 // Then, B should learn the preimage from said transactions, attempting to claim backwards
5749 // B should be able to claim via preimage if A then broadcasts its local tx.
5750 // Finally, when A sees B's latest local commitment transaction it should be able to claim
5751 // the HTLC output via the preimage it learned (which, once confirmed should generate a
5752 // PaymentSent event).
5754 let nodes = create_network(3);
5756 // Create some initial channels
5757 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5758 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5760 // Rebalance the network a bit by relaying one payment through all the channels...
5761 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5762 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5764 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5765 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5767 // Broadcast legit commitment tx from C on B's chain
5768 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
5769 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
5770 assert_eq!(commitment_tx.len(), 1);
5771 check_spends!(commitment_tx[0], chan_2.3.clone());
5772 nodes[2].node.claim_funds(our_payment_preimage);
5773 check_added_monitors!(nodes[2], 1);
5774 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5775 assert!(updates.update_add_htlcs.is_empty());
5776 assert!(updates.update_fail_htlcs.is_empty());
5777 assert!(updates.update_fail_malformed_htlcs.is_empty());
5778 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5780 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5781 let events = nodes[2].node.get_and_clear_pending_msg_events();
5782 assert_eq!(events.len(), 1);
5784 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5785 _ => panic!("Unexpected event"),
5787 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
5788 assert_eq!(node_txn.len(), 3);
5789 assert_eq!(node_txn[1], commitment_tx[0]);
5790 assert_eq!(node_txn[0], node_txn[2]);
5791 check_spends!(node_txn[0], commitment_tx[0].clone());
5792 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5793 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5794 assert_eq!(node_txn[0].lock_time, 0);
5796 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
5797 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
5798 let events = nodes[1].node.get_and_clear_pending_msg_events();
5800 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
5801 assert_eq!(added_monitors.len(), 1);
5802 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
5803 added_monitors.clear();
5805 assert_eq!(events.len(), 2);
5807 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5808 _ => panic!("Unexpected event"),
5811 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
5812 assert!(update_add_htlcs.is_empty());
5813 assert!(update_fail_htlcs.is_empty());
5814 assert_eq!(update_fulfill_htlcs.len(), 1);
5815 assert!(update_fail_malformed_htlcs.is_empty());
5816 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5818 _ => panic!("Unexpected event"),
5821 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
5822 // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
5823 // timeout-claim of the output that nodes[2] just claimed via success.
5824 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 (timeout tx) * 2 (block-rescan)
5825 assert_eq!(node_txn.len(), 4);
5826 assert_eq!(node_txn[0], node_txn[3]);
5827 check_spends!(node_txn[0], commitment_tx[0].clone());
5828 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5829 assert_ne!(node_txn[0].lock_time, 0);
5830 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5831 check_spends!(node_txn[1], chan_2.3.clone());
5832 check_spends!(node_txn[2], node_txn[1].clone());
5833 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5834 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5835 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5836 assert_ne!(node_txn[2].lock_time, 0);
5840 // Broadcast legit commitment tx from A on B's chain
5841 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
5842 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5843 check_spends!(commitment_tx[0], chan_1.3.clone());
5844 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5845 let events = nodes[1].node.get_and_clear_pending_msg_events();
5846 assert_eq!(events.len(), 1);
5848 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5849 _ => panic!("Unexpected event"),
5851 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
5852 assert_eq!(node_txn.len(), 3);
5853 assert_eq!(node_txn[0], node_txn[2]);
5854 check_spends!(node_txn[0], commitment_tx[0].clone());
5855 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5856 assert_eq!(node_txn[0].lock_time, 0);
5857 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5858 check_spends!(node_txn[1], chan_1.3.clone());
5859 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5860 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
5861 // we already checked the same situation with A.
5863 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
5864 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
5865 let events = nodes[0].node.get_and_clear_pending_msg_events();
5866 assert_eq!(events.len(), 1);
5868 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5869 _ => panic!("Unexpected event"),
5871 let events = nodes[0].node.get_and_clear_pending_events();
5872 assert_eq!(events.len(), 1);
5874 Event::PaymentSent { payment_preimage } => {
5875 assert_eq!(payment_preimage, our_payment_preimage);
5877 _ => panic!("Unexpected event"),
5879 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 (HTLC-Timeout tx) * 2 (block-rescan)
5880 assert_eq!(node_txn.len(), 4);
5881 assert_eq!(node_txn[0], node_txn[3]);
5882 check_spends!(node_txn[0], commitment_tx[0].clone());
5883 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5884 assert_ne!(node_txn[0].lock_time, 0);
5885 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5886 check_spends!(node_txn[1], chan_1.3.clone());
5887 check_spends!(node_txn[2], node_txn[1].clone());
5888 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5889 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5890 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5891 assert_ne!(node_txn[2].lock_time, 0);
5895 fn test_htlc_on_chain_timeout() {
5896 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
5897 // ChainWatchInterface and timeout the HTLC bacward accordingly. So here we test that ChannelManager is
5898 // broadcasting the right event to other nodes in payment path.
5899 // A ------------------> B ----------------------> C (timeout)
5900 // B's commitment tx C's commitment tx
5902 // B's HTLC timeout tx B's timeout tx
5904 let nodes = create_network(3);
5906 // Create some intial channels
5907 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5908 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5910 // Rebalance the network a bit by relaying one payment thorugh all the channels...
5911 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5912 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5914 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5915 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5917 // Brodacast legit commitment tx from C on B's chain
5918 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
5919 check_spends!(commitment_tx[0], chan_2.3.clone());
5920 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
5922 let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
5923 assert_eq!(added_monitors.len(), 1);
5924 added_monitors.clear();
5926 let events = nodes[2].node.get_and_clear_pending_msg_events();
5927 assert_eq!(events.len(), 1);
5929 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
5930 assert!(update_add_htlcs.is_empty());
5931 assert!(!update_fail_htlcs.is_empty());
5932 assert!(update_fulfill_htlcs.is_empty());
5933 assert!(update_fail_malformed_htlcs.is_empty());
5934 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
5936 _ => panic!("Unexpected event"),
5938 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5939 let events = nodes[2].node.get_and_clear_pending_msg_events();
5940 assert_eq!(events.len(), 1);
5942 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
5943 _ => panic!("Unexpected event"),
5945 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
5946 assert_eq!(node_txn.len(), 1);
5947 check_spends!(node_txn[0], chan_2.3.clone());
5948 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
5950 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
5951 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
5952 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
5955 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5956 assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
5957 assert_eq!(node_txn[0], node_txn[5]);
5958 assert_eq!(node_txn[1], node_txn[6]);
5959 assert_eq!(node_txn[2], node_txn[7]);
5960 check_spends!(node_txn[0], commitment_tx[0].clone());
5961 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5962 check_spends!(node_txn[1], chan_2.3.clone());
5963 check_spends!(node_txn[2], node_txn[1].clone());
5964 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
5965 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5966 check_spends!(node_txn[3], chan_2.3.clone());
5967 check_spends!(node_txn[4], node_txn[3].clone());
5968 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
5969 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5970 timeout_tx = node_txn[0].clone();
5974 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
5975 let events = nodes[1].node.get_and_clear_pending_msg_events();
5976 check_added_monitors!(nodes[1], 1);
5977 assert_eq!(events.len(), 2);
5979 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
5980 _ => panic!("Unexpected event"),
5983 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
5984 assert!(update_add_htlcs.is_empty());
5985 assert!(!update_fail_htlcs.is_empty());
5986 assert!(update_fulfill_htlcs.is_empty());
5987 assert!(update_fail_malformed_htlcs.is_empty());
5988 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5990 _ => panic!("Unexpected event"),
5992 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
5993 assert_eq!(node_txn.len(), 0);
5995 // Broadcast legit commitment tx from B on A's chain
5996 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5997 check_spends!(commitment_tx[0], chan_1.3.clone());
5999 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6000 let events = nodes[0].node.get_and_clear_pending_msg_events();
6001 assert_eq!(events.len(), 1);
6003 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6004 _ => panic!("Unexpected event"),
6006 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
6007 assert_eq!(node_txn.len(), 4);
6008 assert_eq!(node_txn[0], node_txn[3]);
6009 check_spends!(node_txn[0], commitment_tx[0].clone());
6010 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6011 check_spends!(node_txn[1], chan_1.3.clone());
6012 check_spends!(node_txn[2], node_txn[1].clone());
6013 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6014 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6018 fn test_simple_commitment_revoked_fail_backward() {
6019 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6020 // and fail backward accordingly.
6022 let nodes = create_network(3);
6024 // Create some initial channels
6025 create_announced_chan_between_nodes(&nodes, 0, 1);
6026 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6028 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6029 // Get the will-be-revoked local txn from nodes[2]
6030 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6031 // Revoke the old state
6032 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6034 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6036 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6037 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6038 let events = nodes[1].node.get_and_clear_pending_msg_events();
6039 check_added_monitors!(nodes[1], 1);
6040 assert_eq!(events.len(), 2);
6042 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6043 _ => panic!("Unexpected event"),
6046 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
6047 assert!(update_add_htlcs.is_empty());
6048 assert_eq!(update_fail_htlcs.len(), 1);
6049 assert!(update_fulfill_htlcs.is_empty());
6050 assert!(update_fail_malformed_htlcs.is_empty());
6051 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6053 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6054 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6056 let events = nodes[0].node.get_and_clear_pending_msg_events();
6057 assert_eq!(events.len(), 1);
6059 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6060 _ => panic!("Unexpected event"),
6062 let events = nodes[0].node.get_and_clear_pending_events();
6063 assert_eq!(events.len(), 1);
6065 Event::PaymentFailed { .. } => {},
6066 _ => panic!("Unexpected event"),
6069 _ => panic!("Unexpected event"),
6073 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6074 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6075 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6076 // commitment transaction anymore.
6077 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6078 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6079 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6080 // technically disallowed and we should probably handle it reasonably.
6081 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6082 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6084 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6085 // commitment_signed (implying it will be in the latest remote commitment transaction).
6086 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6087 // and once they revoke the previous commitment transaction (allowing us to send a new
6088 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6089 let mut nodes = create_network(3);
6091 // Create some initial channels
6092 create_announced_chan_between_nodes(&nodes, 0, 1);
6093 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6095 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6096 // Get the will-be-revoked local txn from nodes[2]
6097 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6098 // Revoke the old state
6099 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6101 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6102 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6103 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6105 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, 0));
6106 check_added_monitors!(nodes[2], 1);
6107 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6108 assert!(updates.update_add_htlcs.is_empty());
6109 assert!(updates.update_fulfill_htlcs.is_empty());
6110 assert!(updates.update_fail_malformed_htlcs.is_empty());
6111 assert_eq!(updates.update_fail_htlcs.len(), 1);
6112 assert!(updates.update_fee.is_none());
6113 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6114 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6115 // Drop the last RAA from 3 -> 2
6117 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, 0));
6118 check_added_monitors!(nodes[2], 1);
6119 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6120 assert!(updates.update_add_htlcs.is_empty());
6121 assert!(updates.update_fulfill_htlcs.is_empty());
6122 assert!(updates.update_fail_malformed_htlcs.is_empty());
6123 assert_eq!(updates.update_fail_htlcs.len(), 1);
6124 assert!(updates.update_fee.is_none());
6125 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6126 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6127 check_added_monitors!(nodes[1], 1);
6128 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6129 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6130 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6131 check_added_monitors!(nodes[2], 1);
6133 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, 0));
6134 check_added_monitors!(nodes[2], 1);
6135 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6136 assert!(updates.update_add_htlcs.is_empty());
6137 assert!(updates.update_fulfill_htlcs.is_empty());
6138 assert!(updates.update_fail_malformed_htlcs.is_empty());
6139 assert_eq!(updates.update_fail_htlcs.len(), 1);
6140 assert!(updates.update_fee.is_none());
6141 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6142 // At this point first_payment_hash has dropped out of the latest two commitment
6143 // transactions that nodes[1] is tracking...
6144 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6145 check_added_monitors!(nodes[1], 1);
6146 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6147 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6148 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6149 check_added_monitors!(nodes[2], 1);
6151 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6152 // on nodes[2]'s RAA.
6153 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6154 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6155 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6156 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6157 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6158 check_added_monitors!(nodes[1], 0);
6161 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6162 // One monitor for the new revocation preimage, one as we generate a commitment for
6163 // nodes[0] to fail first_payment_hash backwards.
6164 check_added_monitors!(nodes[1], 2);
6167 let mut failed_htlcs = HashSet::new();
6168 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6170 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6171 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6173 let events = nodes[1].node.get_and_clear_pending_events();
6174 assert_eq!(events.len(), 1);
6176 Event::PaymentFailed { ref payment_hash, .. } => {
6177 assert_eq!(*payment_hash, fourth_payment_hash);
6179 _ => panic!("Unexpected event"),
6182 if !deliver_bs_raa {
6183 // If we delivered the RAA already then we already failed first_payment_hash backwards.
6184 check_added_monitors!(nodes[1], 1);
6187 let events = nodes[1].node.get_and_clear_pending_msg_events();
6188 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6189 match events[if deliver_bs_raa { 2 } else { 0 }] {
6190 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6191 _ => panic!("Unexpected event"),
6195 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
6196 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6197 assert_eq!(update_add_htlcs.len(), 1);
6198 assert!(update_fulfill_htlcs.is_empty());
6199 assert!(update_fail_htlcs.is_empty());
6200 assert!(update_fail_malformed_htlcs.is_empty());
6202 _ => panic!("Unexpected event"),
6205 // Due to the way backwards-failing occurs we do the updates in two steps.
6206 let updates = match events[1] {
6207 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
6208 assert!(update_add_htlcs.is_empty());
6209 assert_eq!(update_fail_htlcs.len(), 1);
6210 assert!(update_fulfill_htlcs.is_empty());
6211 assert!(update_fail_malformed_htlcs.is_empty());
6212 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6215 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6216 check_added_monitors!(nodes[0], 1);
6217 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6218 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6219 check_added_monitors!(nodes[1], 1);
6220 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6221 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6222 check_added_monitors!(nodes[1], 1);
6223 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6224 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6225 check_added_monitors!(nodes[0], 1);
6227 if !deliver_bs_raa {
6228 // If we delievered B's RAA we got an unknown preimage error, not something
6229 // that we should update our routing table for.
6230 let events = nodes[0].node.get_and_clear_pending_msg_events();
6231 assert_eq!(events.len(), 1);
6233 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6234 _ => panic!("Unexpected event"),
6237 let events = nodes[0].node.get_and_clear_pending_events();
6238 assert_eq!(events.len(), 1);
6240 Event::PaymentFailed { ref payment_hash, .. } => {
6241 assert!(failed_htlcs.insert(payment_hash.0));
6243 _ => panic!("Unexpected event"),
6248 _ => panic!("Unexpected event"),
6251 assert!(updates.update_add_htlcs.is_empty());
6252 assert_eq!(updates.update_fail_htlcs.len(), 2);
6253 assert!(updates.update_fulfill_htlcs.is_empty());
6254 assert!(updates.update_fail_malformed_htlcs.is_empty());
6255 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6256 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6257 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6259 let events = nodes[0].node.get_and_clear_pending_msg_events();
6260 assert_eq!(events.len(), 2);
6261 for event in events {
6263 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6264 _ => panic!("Unexpected event"),
6268 let events = nodes[0].node.get_and_clear_pending_events();
6269 assert_eq!(events.len(), 2);
6271 Event::PaymentFailed { ref payment_hash, .. } => {
6272 assert!(failed_htlcs.insert(payment_hash.0));
6274 _ => panic!("Unexpected event"),
6277 Event::PaymentFailed { ref payment_hash, .. } => {
6278 assert!(failed_htlcs.insert(payment_hash.0));
6280 _ => panic!("Unexpected event"),
6283 assert!(failed_htlcs.contains(&first_payment_hash.0));
6284 assert!(failed_htlcs.contains(&second_payment_hash.0));
6285 assert!(failed_htlcs.contains(&third_payment_hash.0));
6289 fn test_commitment_revoked_fail_backward_exhaustive() {
6290 do_test_commitment_revoked_fail_backward_exhaustive(false);
6291 do_test_commitment_revoked_fail_backward_exhaustive(true);
6295 fn test_htlc_ignore_latest_remote_commitment() {
6296 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6297 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6298 let nodes = create_network(2);
6299 create_announced_chan_between_nodes(&nodes, 0, 1);
6301 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6302 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6304 let events = nodes[0].node.get_and_clear_pending_msg_events();
6305 assert_eq!(events.len(), 1);
6307 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6308 assert_eq!(flags & 0b10, 0b10);
6310 _ => panic!("Unexpected event"),
6314 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6315 assert_eq!(node_txn.len(), 2);
6317 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6318 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6321 let events = nodes[1].node.get_and_clear_pending_msg_events();
6322 assert_eq!(events.len(), 1);
6324 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6325 assert_eq!(flags & 0b10, 0b10);
6327 _ => panic!("Unexpected event"),
6331 // Duplicate the block_connected call since this may happen due to other listeners
6332 // registering new transactions
6333 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6337 fn test_force_close_fail_back() {
6338 // Check which HTLCs are failed-backwards on channel force-closure
6339 let mut nodes = create_network(3);
6340 create_announced_chan_between_nodes(&nodes, 0, 1);
6341 create_announced_chan_between_nodes(&nodes, 1, 2);
6343 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6345 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6347 let mut payment_event = {
6348 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6349 check_added_monitors!(nodes[0], 1);
6351 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6352 assert_eq!(events.len(), 1);
6353 SendEvent::from_event(events.remove(0))
6356 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6357 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6359 let events_1 = nodes[1].node.get_and_clear_pending_events();
6360 assert_eq!(events_1.len(), 1);
6362 Event::PendingHTLCsForwardable { .. } => { },
6363 _ => panic!("Unexpected event"),
6366 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6367 nodes[1].node.process_pending_htlc_forwards();
6369 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6370 assert_eq!(events_2.len(), 1);
6371 payment_event = SendEvent::from_event(events_2.remove(0));
6372 assert_eq!(payment_event.msgs.len(), 1);
6374 check_added_monitors!(nodes[1], 1);
6375 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6376 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6377 check_added_monitors!(nodes[2], 1);
6378 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6380 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6381 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6382 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6384 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6385 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6386 assert_eq!(events_3.len(), 1);
6388 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6389 assert_eq!(flags & 0b10, 0b10);
6391 _ => panic!("Unexpected event"),
6395 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6396 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6397 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6398 // back to nodes[1] upon timeout otherwise.
6399 assert_eq!(node_txn.len(), 1);
6403 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6404 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6406 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6407 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6408 assert_eq!(events_4.len(), 1);
6410 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6411 assert_eq!(flags & 0b10, 0b10);
6413 _ => panic!("Unexpected event"),
6416 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6418 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6419 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6420 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6422 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6423 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6424 assert_eq!(node_txn.len(), 1);
6425 assert_eq!(node_txn[0].input.len(), 1);
6426 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6427 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6428 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6430 check_spends!(node_txn[0], tx);
6434 fn test_unconf_chan() {
6435 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6436 let nodes = create_network(2);
6437 create_announced_chan_between_nodes(&nodes, 0, 1);
6439 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6440 assert_eq!(channel_state.by_id.len(), 1);
6441 assert_eq!(channel_state.short_to_id.len(), 1);
6442 mem::drop(channel_state);
6444 let mut headers = Vec::new();
6445 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6446 headers.push(header.clone());
6448 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6449 headers.push(header.clone());
6451 while !headers.is_empty() {
6452 nodes[0].node.block_disconnected(&headers.pop().unwrap());
6455 let events = nodes[0].node.get_and_clear_pending_msg_events();
6456 assert_eq!(events.len(), 1);
6458 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6459 assert_eq!(flags & 0b10, 0b10);
6461 _ => panic!("Unexpected event"),
6464 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6465 assert_eq!(channel_state.by_id.len(), 0);
6466 assert_eq!(channel_state.short_to_id.len(), 0);
6469 macro_rules! get_chan_reestablish_msgs {
6470 ($src_node: expr, $dst_node: expr) => {
6472 let mut res = Vec::with_capacity(1);
6473 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6474 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6475 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6476 res.push(msg.clone());
6478 panic!("Unexpected event")
6486 macro_rules! handle_chan_reestablish_msgs {
6487 ($src_node: expr, $dst_node: expr) => {
6489 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6491 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6493 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6499 let mut revoke_and_ack = None;
6500 let mut commitment_update = None;
6501 let order = if let Some(ev) = msg_events.get(idx) {
6504 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6505 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6506 revoke_and_ack = Some(msg.clone());
6507 RAACommitmentOrder::RevokeAndACKFirst
6509 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6510 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6511 commitment_update = Some(updates.clone());
6512 RAACommitmentOrder::CommitmentFirst
6514 _ => panic!("Unexpected event"),
6517 RAACommitmentOrder::CommitmentFirst
6520 if let Some(ev) = msg_events.get(idx) {
6522 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6523 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6524 assert!(revoke_and_ack.is_none());
6525 revoke_and_ack = Some(msg.clone());
6527 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6528 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6529 assert!(commitment_update.is_none());
6530 commitment_update = Some(updates.clone());
6532 _ => panic!("Unexpected event"),
6536 (funding_locked, revoke_and_ack, commitment_update, order)
6541 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6542 /// for claims/fails they are separated out.
6543 fn reconnect_nodes(node_a: &Node, node_b: &Node, send_funding_locked: (bool, 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)) {
6544 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6545 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6546 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6547 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6549 if send_funding_locked.0 {
6550 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6552 for reestablish in reestablish_1.iter() {
6553 assert_eq!(reestablish.next_remote_commitment_number, 0);
6556 if send_funding_locked.1 {
6557 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6559 for reestablish in reestablish_2.iter() {
6560 assert_eq!(reestablish.next_remote_commitment_number, 0);
6563 if send_funding_locked.0 || send_funding_locked.1 {
6564 // If we expect any funding_locked's, both sides better have set
6565 // next_local_commitment_number to 1
6566 for reestablish in reestablish_1.iter() {
6567 assert_eq!(reestablish.next_local_commitment_number, 1);
6569 for reestablish in reestablish_2.iter() {
6570 assert_eq!(reestablish.next_local_commitment_number, 1);
6574 let mut resp_1 = Vec::new();
6575 for msg in reestablish_1 {
6576 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6577 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6579 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6580 check_added_monitors!(node_b, 1);
6582 check_added_monitors!(node_b, 0);
6585 let mut resp_2 = Vec::new();
6586 for msg in reestablish_2 {
6587 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6588 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6590 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6591 check_added_monitors!(node_a, 1);
6593 check_added_monitors!(node_a, 0);
6596 // We dont yet support both needing updates, as that would require a different commitment dance:
6597 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
6598 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
6600 for chan_msgs in resp_1.drain(..) {
6601 if send_funding_locked.0 {
6602 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6603 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
6604 if !announcement_event.is_empty() {
6605 assert_eq!(announcement_event.len(), 1);
6606 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6607 //TODO: Test announcement_sigs re-sending
6608 } else { panic!("Unexpected event!"); }
6611 assert!(chan_msgs.0.is_none());
6614 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6615 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6616 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6617 check_added_monitors!(node_a, 1);
6619 assert!(chan_msgs.1.is_none());
6621 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6622 let commitment_update = chan_msgs.2.unwrap();
6623 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6624 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
6626 assert!(commitment_update.update_add_htlcs.is_empty());
6628 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6629 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6630 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6631 for update_add in commitment_update.update_add_htlcs {
6632 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
6634 for update_fulfill in commitment_update.update_fulfill_htlcs {
6635 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
6637 for update_fail in commitment_update.update_fail_htlcs {
6638 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
6641 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6642 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
6644 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6645 check_added_monitors!(node_a, 1);
6646 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
6647 // No commitment_signed so get_event_msg's assert(len == 1) passes
6648 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6649 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6650 check_added_monitors!(node_b, 1);
6653 assert!(chan_msgs.2.is_none());
6657 for chan_msgs in resp_2.drain(..) {
6658 if send_funding_locked.1 {
6659 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6660 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
6661 if !announcement_event.is_empty() {
6662 assert_eq!(announcement_event.len(), 1);
6663 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6664 //TODO: Test announcement_sigs re-sending
6665 } else { panic!("Unexpected event!"); }
6668 assert!(chan_msgs.0.is_none());
6671 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6672 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6673 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6674 check_added_monitors!(node_b, 1);
6676 assert!(chan_msgs.1.is_none());
6678 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6679 let commitment_update = chan_msgs.2.unwrap();
6680 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6681 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
6683 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6684 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6685 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6686 for update_add in commitment_update.update_add_htlcs {
6687 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
6689 for update_fulfill in commitment_update.update_fulfill_htlcs {
6690 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
6692 for update_fail in commitment_update.update_fail_htlcs {
6693 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
6696 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6697 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
6699 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6700 check_added_monitors!(node_b, 1);
6701 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
6702 // No commitment_signed so get_event_msg's assert(len == 1) passes
6703 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6704 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6705 check_added_monitors!(node_a, 1);
6708 assert!(chan_msgs.2.is_none());
6714 fn test_simple_peer_disconnect() {
6715 // Test that we can reconnect when there are no lost messages
6716 let nodes = create_network(3);
6717 create_announced_chan_between_nodes(&nodes, 0, 1);
6718 create_announced_chan_between_nodes(&nodes, 1, 2);
6720 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6721 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6722 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6724 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6725 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6726 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
6727 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
6729 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6730 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6731 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6733 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6734 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6735 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6736 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6738 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6739 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6741 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
6742 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
6744 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
6746 let events = nodes[0].node.get_and_clear_pending_events();
6747 assert_eq!(events.len(), 2);
6749 Event::PaymentSent { payment_preimage } => {
6750 assert_eq!(payment_preimage, payment_preimage_3);
6752 _ => panic!("Unexpected event"),
6755 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
6756 assert_eq!(payment_hash, payment_hash_5);
6757 assert!(rejected_by_dest);
6759 _ => panic!("Unexpected event"),
6763 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
6764 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
6767 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
6768 // Test that we can reconnect when in-flight HTLC updates get dropped
6769 let mut nodes = create_network(2);
6770 if messages_delivered == 0 {
6771 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
6772 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
6774 create_announced_chan_between_nodes(&nodes, 0, 1);
6777 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();
6778 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6780 let payment_event = {
6781 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
6782 check_added_monitors!(nodes[0], 1);
6784 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6785 assert_eq!(events.len(), 1);
6786 SendEvent::from_event(events.remove(0))
6788 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
6790 if messages_delivered < 2 {
6791 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
6793 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6794 if messages_delivered >= 3 {
6795 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6796 check_added_monitors!(nodes[1], 1);
6797 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6799 if messages_delivered >= 4 {
6800 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6801 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6802 check_added_monitors!(nodes[0], 1);
6804 if messages_delivered >= 5 {
6805 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
6806 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6807 // No commitment_signed so get_event_msg's assert(len == 1) passes
6808 check_added_monitors!(nodes[0], 1);
6810 if messages_delivered >= 6 {
6811 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6812 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6813 check_added_monitors!(nodes[1], 1);
6820 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6821 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6822 if messages_delivered < 3 {
6823 // Even if the funding_locked messages get exchanged, as long as nothing further was
6824 // received on either side, both sides will need to resend them.
6825 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
6826 } else if messages_delivered == 3 {
6827 // nodes[0] still wants its RAA + commitment_signed
6828 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
6829 } else if messages_delivered == 4 {
6830 // nodes[0] still wants its commitment_signed
6831 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
6832 } else if messages_delivered == 5 {
6833 // nodes[1] still wants its final RAA
6834 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
6835 } else if messages_delivered == 6 {
6836 // Everything was delivered...
6837 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6840 let events_1 = nodes[1].node.get_and_clear_pending_events();
6841 assert_eq!(events_1.len(), 1);
6843 Event::PendingHTLCsForwardable { .. } => { },
6844 _ => panic!("Unexpected event"),
6847 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6848 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6849 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6851 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6852 nodes[1].node.process_pending_htlc_forwards();
6854 let events_2 = nodes[1].node.get_and_clear_pending_events();
6855 assert_eq!(events_2.len(), 1);
6857 Event::PaymentReceived { ref payment_hash, amt } => {
6858 assert_eq!(payment_hash_1, *payment_hash);
6859 assert_eq!(amt, 1000000);
6861 _ => panic!("Unexpected event"),
6864 nodes[1].node.claim_funds(payment_preimage_1);
6865 check_added_monitors!(nodes[1], 1);
6867 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
6868 assert_eq!(events_3.len(), 1);
6869 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
6870 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6871 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6872 assert!(updates.update_add_htlcs.is_empty());
6873 assert!(updates.update_fail_htlcs.is_empty());
6874 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6875 assert!(updates.update_fail_malformed_htlcs.is_empty());
6876 assert!(updates.update_fee.is_none());
6877 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
6879 _ => panic!("Unexpected event"),
6882 if messages_delivered >= 1 {
6883 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
6885 let events_4 = nodes[0].node.get_and_clear_pending_events();
6886 assert_eq!(events_4.len(), 1);
6888 Event::PaymentSent { ref payment_preimage } => {
6889 assert_eq!(payment_preimage_1, *payment_preimage);
6891 _ => panic!("Unexpected event"),
6894 if messages_delivered >= 2 {
6895 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
6896 check_added_monitors!(nodes[0], 1);
6897 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6899 if messages_delivered >= 3 {
6900 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6901 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6902 check_added_monitors!(nodes[1], 1);
6904 if messages_delivered >= 4 {
6905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6906 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6907 // No commitment_signed so get_event_msg's assert(len == 1) passes
6908 check_added_monitors!(nodes[1], 1);
6910 if messages_delivered >= 5 {
6911 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6912 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6913 check_added_monitors!(nodes[0], 1);
6920 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6921 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6922 if messages_delivered < 2 {
6923 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
6924 //TODO: Deduplicate PaymentSent events, then enable this if:
6925 //if messages_delivered < 1 {
6926 let events_4 = nodes[0].node.get_and_clear_pending_events();
6927 assert_eq!(events_4.len(), 1);
6929 Event::PaymentSent { ref payment_preimage } => {
6930 assert_eq!(payment_preimage_1, *payment_preimage);
6932 _ => panic!("Unexpected event"),
6935 } else if messages_delivered == 2 {
6936 // nodes[0] still wants its RAA + commitment_signed
6937 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
6938 } else if messages_delivered == 3 {
6939 // nodes[0] still wants its commitment_signed
6940 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
6941 } else if messages_delivered == 4 {
6942 // nodes[1] still wants its final RAA
6943 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
6944 } else if messages_delivered == 5 {
6945 // Everything was delivered...
6946 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6949 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6950 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6951 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6953 // Channel should still work fine...
6954 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
6955 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
6959 fn test_drop_messages_peer_disconnect_a() {
6960 do_test_drop_messages_peer_disconnect(0);
6961 do_test_drop_messages_peer_disconnect(1);
6962 do_test_drop_messages_peer_disconnect(2);
6963 do_test_drop_messages_peer_disconnect(3);
6967 fn test_drop_messages_peer_disconnect_b() {
6968 do_test_drop_messages_peer_disconnect(4);
6969 do_test_drop_messages_peer_disconnect(5);
6970 do_test_drop_messages_peer_disconnect(6);
6974 fn test_funding_peer_disconnect() {
6975 // Test that we can lock in our funding tx while disconnected
6976 let nodes = create_network(2);
6977 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
6979 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6980 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6982 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
6983 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
6984 assert_eq!(events_1.len(), 1);
6986 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
6987 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6989 _ => panic!("Unexpected event"),
6992 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6994 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6995 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6997 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
6998 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6999 assert_eq!(events_2.len(), 2);
7001 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7002 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7004 _ => panic!("Unexpected event"),
7007 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7008 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7010 _ => panic!("Unexpected event"),
7013 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7015 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7016 // rebroadcasting announcement_signatures upon reconnect.
7018 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();
7019 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7020 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7024 fn test_drop_messages_peer_disconnect_dual_htlc() {
7025 // Test that we can handle reconnecting when both sides of a channel have pending
7026 // commitment_updates when we disconnect.
7027 let mut nodes = create_network(2);
7028 create_announced_chan_between_nodes(&nodes, 0, 1);
7030 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7032 // Now try to send a second payment which will fail to send
7033 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7034 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7036 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7037 check_added_monitors!(nodes[0], 1);
7039 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7040 assert_eq!(events_1.len(), 1);
7042 MessageSendEvent::UpdateHTLCs { .. } => {},
7043 _ => panic!("Unexpected event"),
7046 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7047 check_added_monitors!(nodes[1], 1);
7049 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7050 assert_eq!(events_2.len(), 1);
7052 MessageSendEvent::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 } } => {
7053 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7054 assert!(update_add_htlcs.is_empty());
7055 assert_eq!(update_fulfill_htlcs.len(), 1);
7056 assert!(update_fail_htlcs.is_empty());
7057 assert!(update_fail_malformed_htlcs.is_empty());
7058 assert!(update_fee.is_none());
7060 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7061 let events_3 = nodes[0].node.get_and_clear_pending_events();
7062 assert_eq!(events_3.len(), 1);
7064 Event::PaymentSent { ref payment_preimage } => {
7065 assert_eq!(*payment_preimage, payment_preimage_1);
7067 _ => panic!("Unexpected event"),
7070 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7071 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7072 // No commitment_signed so get_event_msg's assert(len == 1) passes
7073 check_added_monitors!(nodes[0], 1);
7075 _ => panic!("Unexpected event"),
7078 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7079 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7081 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7082 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7083 assert_eq!(reestablish_1.len(), 1);
7084 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7085 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7086 assert_eq!(reestablish_2.len(), 1);
7088 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7089 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7090 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7091 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7093 assert!(as_resp.0.is_none());
7094 assert!(bs_resp.0.is_none());
7096 assert!(bs_resp.1.is_none());
7097 assert!(bs_resp.2.is_none());
7099 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7101 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7102 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7103 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7104 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7105 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7106 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
7107 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7108 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7109 // No commitment_signed so get_event_msg's assert(len == 1) passes
7110 check_added_monitors!(nodes[1], 1);
7112 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7113 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7114 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7115 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7116 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7117 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7118 assert!(bs_second_commitment_signed.update_fee.is_none());
7119 check_added_monitors!(nodes[1], 1);
7121 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7122 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7123 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7124 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7125 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7126 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7127 assert!(as_commitment_signed.update_fee.is_none());
7128 check_added_monitors!(nodes[0], 1);
7130 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7131 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7132 // No commitment_signed so get_event_msg's assert(len == 1) passes
7133 check_added_monitors!(nodes[0], 1);
7135 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7136 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7137 // No commitment_signed so get_event_msg's assert(len == 1) passes
7138 check_added_monitors!(nodes[1], 1);
7140 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7141 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7142 check_added_monitors!(nodes[1], 1);
7144 let events_4 = nodes[1].node.get_and_clear_pending_events();
7145 assert_eq!(events_4.len(), 1);
7147 Event::PendingHTLCsForwardable { .. } => { },
7148 _ => panic!("Unexpected event"),
7151 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7152 nodes[1].node.process_pending_htlc_forwards();
7154 let events_5 = nodes[1].node.get_and_clear_pending_events();
7155 assert_eq!(events_5.len(), 1);
7157 Event::PaymentReceived { ref payment_hash, amt: _ } => {
7158 assert_eq!(payment_hash_2, *payment_hash);
7160 _ => panic!("Unexpected event"),
7163 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7164 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7165 check_added_monitors!(nodes[0], 1);
7167 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7171 fn test_simple_monitor_permanent_update_fail() {
7172 // Test that we handle a simple permanent monitor update failure
7173 let mut nodes = create_network(2);
7174 create_announced_chan_between_nodes(&nodes, 0, 1);
7176 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7177 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7179 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7180 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7181 check_added_monitors!(nodes[0], 1);
7183 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7184 assert_eq!(events_1.len(), 2);
7186 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7187 _ => panic!("Unexpected event"),
7190 MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7191 _ => panic!("Unexpected event"),
7194 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7195 // PaymentFailed event
7197 assert_eq!(nodes[0].node.list_channels().len(), 0);
7200 fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7201 // Test that we can recover from a simple temporary monitor update failure optionally with
7202 // a disconnect in between
7203 let mut nodes = create_network(2);
7204 create_announced_chan_between_nodes(&nodes, 0, 1);
7206 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7207 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7209 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7210 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7211 check_added_monitors!(nodes[0], 1);
7213 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7214 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7215 assert_eq!(nodes[0].node.list_channels().len(), 1);
7218 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7219 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7220 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7223 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7224 nodes[0].node.test_restore_channel_monitor();
7225 check_added_monitors!(nodes[0], 1);
7227 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7228 assert_eq!(events_2.len(), 1);
7229 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7230 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7231 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7232 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7234 expect_pending_htlcs_forwardable!(nodes[1]);
7236 let events_3 = nodes[1].node.get_and_clear_pending_events();
7237 assert_eq!(events_3.len(), 1);
7239 Event::PaymentReceived { ref payment_hash, amt } => {
7240 assert_eq!(payment_hash_1, *payment_hash);
7241 assert_eq!(amt, 1000000);
7243 _ => panic!("Unexpected event"),
7246 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7248 // Now set it to failed again...
7249 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7250 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7251 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7252 check_added_monitors!(nodes[0], 1);
7254 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7255 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7256 assert_eq!(nodes[0].node.list_channels().len(), 1);
7259 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7260 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7261 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7264 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7265 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7266 nodes[0].node.test_restore_channel_monitor();
7267 check_added_monitors!(nodes[0], 1);
7269 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7270 assert_eq!(events_5.len(), 1);
7272 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7273 _ => panic!("Unexpected event"),
7276 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7277 // PaymentFailed event
7279 assert_eq!(nodes[0].node.list_channels().len(), 0);
7283 fn test_simple_monitor_temporary_update_fail() {
7284 do_test_simple_monitor_temporary_update_fail(false);
7285 do_test_simple_monitor_temporary_update_fail(true);
7288 fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7289 let disconnect_flags = 8 | 16;
7291 // Test that we can recover from a temporary monitor update failure with some in-flight
7292 // HTLCs going on at the same time potentially with some disconnection thrown in.
7293 // * First we route a payment, then get a temporary monitor update failure when trying to
7294 // route a second payment. We then claim the first payment.
7295 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7296 // TemporaryFailure likely indicates net disconnect which resulted in failing to update
7297 // the ChannelMonitor on a watchtower).
7298 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7299 // immediately, otherwise we wait sconnect and deliver them via the reconnect
7300 // channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7301 // disconnect_count & !disconnect_flags is 0).
7302 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7303 // through message sending, potentially disconnect/reconnecting multiple times based on
7304 // disconnect_count, to get the update_fulfill_htlc through.
7305 // * We then walk through more message exchanges to get the original update_add_htlc
7306 // through, swapping message ordering based on disconnect_count & 8 and optionally
7307 // disconnect/reconnecting based on disconnect_count.
7308 let mut nodes = create_network(2);
7309 create_announced_chan_between_nodes(&nodes, 0, 1);
7311 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7313 // Now try to send a second payment which will fail to send
7314 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7315 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7317 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7318 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7319 check_added_monitors!(nodes[0], 1);
7321 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7322 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7323 assert_eq!(nodes[0].node.list_channels().len(), 1);
7325 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7326 // but nodes[0] won't respond since it is frozen.
7327 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7328 check_added_monitors!(nodes[1], 1);
7329 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7330 assert_eq!(events_2.len(), 1);
7331 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7332 MessageSendEvent::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 } } => {
7333 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7334 assert!(update_add_htlcs.is_empty());
7335 assert_eq!(update_fulfill_htlcs.len(), 1);
7336 assert!(update_fail_htlcs.is_empty());
7337 assert!(update_fail_malformed_htlcs.is_empty());
7338 assert!(update_fee.is_none());
7340 if (disconnect_count & 16) == 0 {
7341 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7342 let events_3 = nodes[0].node.get_and_clear_pending_events();
7343 assert_eq!(events_3.len(), 1);
7345 Event::PaymentSent { ref payment_preimage } => {
7346 assert_eq!(*payment_preimage, payment_preimage_1);
7348 _ => panic!("Unexpected event"),
7351 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::IgnoreError) }) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed) {
7352 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7353 } else { panic!(); }
7356 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7358 _ => panic!("Unexpected event"),
7361 if disconnect_count & !disconnect_flags > 0 {
7362 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7363 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7366 // Now fix monitor updating...
7367 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7368 nodes[0].node.test_restore_channel_monitor();
7369 check_added_monitors!(nodes[0], 1);
7371 macro_rules! disconnect_reconnect_peers { () => { {
7372 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7373 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7375 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7376 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7377 assert_eq!(reestablish_1.len(), 1);
7378 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7379 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7380 assert_eq!(reestablish_2.len(), 1);
7382 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7383 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7384 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7385 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7387 assert!(as_resp.0.is_none());
7388 assert!(bs_resp.0.is_none());
7390 (reestablish_1, reestablish_2, as_resp, bs_resp)
7393 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7394 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7395 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7397 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7398 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7399 assert_eq!(reestablish_1.len(), 1);
7400 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7401 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7402 assert_eq!(reestablish_2.len(), 1);
7404 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7405 check_added_monitors!(nodes[0], 0);
7406 let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7407 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7408 check_added_monitors!(nodes[1], 0);
7409 let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7411 assert!(as_resp.0.is_none());
7412 assert!(bs_resp.0.is_none());
7414 assert!(bs_resp.1.is_none());
7415 if (disconnect_count & 16) == 0 {
7416 assert!(bs_resp.2.is_none());
7418 assert!(as_resp.1.is_some());
7419 assert!(as_resp.2.is_some());
7420 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7422 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7423 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7424 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7425 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7426 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7427 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7429 assert!(as_resp.1.is_none());
7431 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().update_fulfill_htlcs[0]).unwrap();
7432 let events_3 = nodes[0].node.get_and_clear_pending_events();
7433 assert_eq!(events_3.len(), 1);
7435 Event::PaymentSent { ref payment_preimage } => {
7436 assert_eq!(*payment_preimage, payment_preimage_1);
7438 _ => panic!("Unexpected event"),
7441 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7442 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7443 // No commitment_signed so get_event_msg's assert(len == 1) passes
7444 check_added_monitors!(nodes[0], 1);
7446 as_resp.1 = Some(as_resp_raa);
7450 if disconnect_count & !disconnect_flags > 1 {
7451 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7453 if (disconnect_count & 16) == 0 {
7454 assert!(reestablish_1 == second_reestablish_1);
7455 assert!(reestablish_2 == second_reestablish_2);
7457 assert!(as_resp == second_as_resp);
7458 assert!(bs_resp == second_bs_resp);
7461 (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7463 let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7464 assert_eq!(events_4.len(), 2);
7465 (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7466 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7467 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7470 _ => panic!("Unexpected event"),
7474 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7476 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7477 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7478 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7479 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7480 check_added_monitors!(nodes[1], 1);
7482 if disconnect_count & !disconnect_flags > 2 {
7483 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7485 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7486 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7488 assert!(as_resp.2.is_none());
7489 assert!(bs_resp.2.is_none());
7492 let as_commitment_update;
7493 let bs_second_commitment_update;
7495 macro_rules! handle_bs_raa { () => {
7496 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7497 as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7498 assert!(as_commitment_update.update_add_htlcs.is_empty());
7499 assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7500 assert!(as_commitment_update.update_fail_htlcs.is_empty());
7501 assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7502 assert!(as_commitment_update.update_fee.is_none());
7503 check_added_monitors!(nodes[0], 1);
7506 macro_rules! handle_initial_raa { () => {
7507 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7508 bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7509 assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7510 assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7511 assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7512 assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7513 assert!(bs_second_commitment_update.update_fee.is_none());
7514 check_added_monitors!(nodes[1], 1);
7517 if (disconnect_count & 8) == 0 {
7520 if disconnect_count & !disconnect_flags > 3 {
7521 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7523 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7524 assert!(bs_resp.1.is_none());
7526 assert!(as_resp.2.unwrap() == as_commitment_update);
7527 assert!(bs_resp.2.is_none());
7529 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7532 handle_initial_raa!();
7534 if disconnect_count & !disconnect_flags > 4 {
7535 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7537 assert!(as_resp.1.is_none());
7538 assert!(bs_resp.1.is_none());
7540 assert!(as_resp.2.unwrap() == as_commitment_update);
7541 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7544 handle_initial_raa!();
7546 if disconnect_count & !disconnect_flags > 3 {
7547 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7549 assert!(as_resp.1.is_none());
7550 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7552 assert!(as_resp.2.is_none());
7553 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7555 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7560 if disconnect_count & !disconnect_flags > 4 {
7561 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7563 assert!(as_resp.1.is_none());
7564 assert!(bs_resp.1.is_none());
7566 assert!(as_resp.2.unwrap() == as_commitment_update);
7567 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7571 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7572 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7573 // No commitment_signed so get_event_msg's assert(len == 1) passes
7574 check_added_monitors!(nodes[0], 1);
7576 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7577 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7578 // No commitment_signed so get_event_msg's assert(len == 1) passes
7579 check_added_monitors!(nodes[1], 1);
7581 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7582 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7583 check_added_monitors!(nodes[1], 1);
7585 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7586 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7587 check_added_monitors!(nodes[0], 1);
7589 expect_pending_htlcs_forwardable!(nodes[1]);
7591 let events_5 = nodes[1].node.get_and_clear_pending_events();
7592 assert_eq!(events_5.len(), 1);
7594 Event::PaymentReceived { ref payment_hash, amt } => {
7595 assert_eq!(payment_hash_2, *payment_hash);
7596 assert_eq!(amt, 1000000);
7598 _ => panic!("Unexpected event"),
7601 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7605 fn test_monitor_temporary_update_fail_a() {
7606 do_test_monitor_temporary_update_fail(0);
7607 do_test_monitor_temporary_update_fail(1);
7608 do_test_monitor_temporary_update_fail(2);
7609 do_test_monitor_temporary_update_fail(3);
7610 do_test_monitor_temporary_update_fail(4);
7611 do_test_monitor_temporary_update_fail(5);
7615 fn test_monitor_temporary_update_fail_b() {
7616 do_test_monitor_temporary_update_fail(2 | 8);
7617 do_test_monitor_temporary_update_fail(3 | 8);
7618 do_test_monitor_temporary_update_fail(4 | 8);
7619 do_test_monitor_temporary_update_fail(5 | 8);
7623 fn test_monitor_temporary_update_fail_c() {
7624 do_test_monitor_temporary_update_fail(1 | 16);
7625 do_test_monitor_temporary_update_fail(2 | 16);
7626 do_test_monitor_temporary_update_fail(3 | 16);
7627 do_test_monitor_temporary_update_fail(2 | 8 | 16);
7628 do_test_monitor_temporary_update_fail(3 | 8 | 16);
7632 fn test_monitor_update_fail_cs() {
7633 // Tests handling of a monitor update failure when processing an incoming commitment_signed
7634 let mut nodes = create_network(2);
7635 create_announced_chan_between_nodes(&nodes, 0, 1);
7637 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7638 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7639 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
7640 check_added_monitors!(nodes[0], 1);
7642 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7643 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7645 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7646 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_event.commitment_msg).unwrap_err() {
7647 assert_eq!(err, "Failed to update ChannelMonitor");
7648 } else { panic!(); }
7649 check_added_monitors!(nodes[1], 1);
7650 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7652 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
7653 nodes[1].node.test_restore_channel_monitor();
7654 check_added_monitors!(nodes[1], 1);
7655 let responses = nodes[1].node.get_and_clear_pending_msg_events();
7656 assert_eq!(responses.len(), 2);
7658 match responses[0] {
7659 MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
7660 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7661 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
7662 check_added_monitors!(nodes[0], 1);
7664 _ => panic!("Unexpected event"),
7666 match responses[1] {
7667 MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
7668 assert!(updates.update_add_htlcs.is_empty());
7669 assert!(updates.update_fulfill_htlcs.is_empty());
7670 assert!(updates.update_fail_htlcs.is_empty());
7671 assert!(updates.update_fail_malformed_htlcs.is_empty());
7672 assert!(updates.update_fee.is_none());
7673 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7675 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7676 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed).unwrap_err() {
7677 assert_eq!(err, "Failed to update ChannelMonitor");
7678 } else { panic!(); }
7679 check_added_monitors!(nodes[0], 1);
7680 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7682 _ => panic!("Unexpected event"),
7685 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7686 nodes[0].node.test_restore_channel_monitor();
7687 check_added_monitors!(nodes[0], 1);
7689 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7690 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
7691 check_added_monitors!(nodes[1], 1);
7693 let mut events = nodes[1].node.get_and_clear_pending_events();
7694 assert_eq!(events.len(), 1);
7696 Event::PendingHTLCsForwardable { .. } => { },
7697 _ => panic!("Unexpected event"),
7699 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7700 nodes[1].node.process_pending_htlc_forwards();
7702 events = nodes[1].node.get_and_clear_pending_events();
7703 assert_eq!(events.len(), 1);
7705 Event::PaymentReceived { payment_hash, amt } => {
7706 assert_eq!(payment_hash, our_payment_hash);
7707 assert_eq!(amt, 1000000);
7709 _ => panic!("Unexpected event"),
7712 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7715 fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
7716 // Tests handling of a monitor update failure when processing an incoming RAA
7717 let mut nodes = create_network(3);
7718 create_announced_chan_between_nodes(&nodes, 0, 1);
7719 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
7721 // Rebalance a bit so that we can send backwards from 2 to 1.
7722 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
7724 // Route a first payment that we'll fail backwards
7725 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
7727 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
7728 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, 0));
7729 check_added_monitors!(nodes[2], 1);
7731 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
7732 assert!(updates.update_add_htlcs.is_empty());
7733 assert!(updates.update_fulfill_htlcs.is_empty());
7734 assert_eq!(updates.update_fail_htlcs.len(), 1);
7735 assert!(updates.update_fail_malformed_htlcs.is_empty());
7736 assert!(updates.update_fee.is_none());
7737 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
7739 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
7740 check_added_monitors!(nodes[0], 0);
7742 // While the second channel is AwaitingRAA, forward a second payment to get it into the
7744 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7745 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7746 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
7747 check_added_monitors!(nodes[0], 1);
7749 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7750 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7751 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
7753 let events_1 = nodes[1].node.get_and_clear_pending_events();
7754 assert_eq!(events_1.len(), 1);
7756 Event::PendingHTLCsForwardable { .. } => { },
7757 _ => panic!("Unexpected event"),
7760 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7761 nodes[1].node.process_pending_htlc_forwards();
7762 check_added_monitors!(nodes[1], 0);
7763 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7765 // Now fail monitor updating.
7766 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7767 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap_err() {
7768 assert_eq!(err, "Failed to update ChannelMonitor");
7769 } else { panic!(); }
7770 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7771 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7772 check_added_monitors!(nodes[1], 1);
7774 // Attempt to forward a third payment but fail due to the second channel being unavailable
7777 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
7778 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7779 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
7780 check_added_monitors!(nodes[0], 1);
7782 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
7783 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7785 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
7786 check_added_monitors!(nodes[1], 0);
7788 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7789 assert_eq!(events_2.len(), 1);
7790 match events_2.remove(0) {
7791 MessageSendEvent::UpdateHTLCs { node_id, updates } => {
7792 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7793 assert!(updates.update_fulfill_htlcs.is_empty());
7794 assert_eq!(updates.update_fail_htlcs.len(), 1);
7795 assert!(updates.update_fail_malformed_htlcs.is_empty());
7796 assert!(updates.update_add_htlcs.is_empty());
7797 assert!(updates.update_fee.is_none());
7799 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
7800 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7802 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7803 assert_eq!(msg_events.len(), 1);
7804 match msg_events[0] {
7805 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
7806 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
7807 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
7809 _ => panic!("Unexpected event"),
7812 let events = nodes[0].node.get_and_clear_pending_events();
7813 assert_eq!(events.len(), 1);
7814 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
7815 assert_eq!(payment_hash, payment_hash_3);
7816 assert!(!rejected_by_dest);
7817 } else { panic!("Unexpected event!"); }
7819 _ => panic!("Unexpected event type!"),
7822 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
7823 // Try to route another payment backwards from 2 to make sure 1 holds off on responding
7824 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
7825 let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7826 nodes[2].node.send_payment(route, payment_hash_4).unwrap();
7827 check_added_monitors!(nodes[2], 1);
7829 send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
7830 nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7831 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::IgnoreError) }) = nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &send_event.commitment_msg) {
7832 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7833 } else { panic!(); }
7834 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7835 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7836 (Some(payment_preimage_4), Some(payment_hash_4))
7837 } else { (None, None) };
7839 // Restore monitor updating, ensuring we immediately get a fail-back update and a
7840 // update_add update.
7841 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
7842 nodes[1].node.test_restore_channel_monitor();
7843 check_added_monitors!(nodes[1], 2);
7845 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7846 if test_ignore_second_cs {
7847 assert_eq!(events_3.len(), 3);
7849 assert_eq!(events_3.len(), 2);
7852 // Note that the ordering of the events for different nodes is non-prescriptive, though the
7853 // ordering of the two events that both go to nodes[2] have to stay in the same order.
7854 let messages_a = match events_3.pop().unwrap() {
7855 MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
7856 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7857 assert!(updates.update_fulfill_htlcs.is_empty());
7858 assert_eq!(updates.update_fail_htlcs.len(), 1);
7859 assert!(updates.update_fail_malformed_htlcs.is_empty());
7860 assert!(updates.update_add_htlcs.is_empty());
7861 assert!(updates.update_fee.is_none());
7862 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
7864 _ => panic!("Unexpected event type!"),
7866 let raa = if test_ignore_second_cs {
7867 match events_3.remove(1) {
7868 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
7869 assert_eq!(node_id, nodes[2].node.get_our_node_id());
7872 _ => panic!("Unexpected event"),
7875 let send_event_b = SendEvent::from_event(events_3.remove(0));
7876 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
7878 // Now deliver the new messages...
7880 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
7881 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
7882 let events_4 = nodes[0].node.get_and_clear_pending_events();
7883 assert_eq!(events_4.len(), 1);
7884 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
7885 assert_eq!(payment_hash, payment_hash_1);
7886 assert!(rejected_by_dest);
7887 } else { panic!("Unexpected event!"); }
7889 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
7890 if test_ignore_second_cs {
7891 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
7892 check_added_monitors!(nodes[2], 1);
7893 let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7894 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
7895 check_added_monitors!(nodes[2], 1);
7896 let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
7897 assert!(bs_cs.update_add_htlcs.is_empty());
7898 assert!(bs_cs.update_fail_htlcs.is_empty());
7899 assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
7900 assert!(bs_cs.update_fulfill_htlcs.is_empty());
7901 assert!(bs_cs.update_fee.is_none());
7903 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7904 check_added_monitors!(nodes[1], 1);
7905 let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
7906 assert!(as_cs.update_add_htlcs.is_empty());
7907 assert!(as_cs.update_fail_htlcs.is_empty());
7908 assert!(as_cs.update_fail_malformed_htlcs.is_empty());
7909 assert!(as_cs.update_fulfill_htlcs.is_empty());
7910 assert!(as_cs.update_fee.is_none());
7912 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
7913 check_added_monitors!(nodes[1], 1);
7914 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
7916 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
7917 check_added_monitors!(nodes[2], 1);
7918 let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7920 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
7921 check_added_monitors!(nodes[2], 1);
7922 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
7924 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
7925 check_added_monitors!(nodes[1], 1);
7926 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7928 commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
7931 let events_5 = nodes[2].node.get_and_clear_pending_events();
7932 assert_eq!(events_5.len(), 1);
7934 Event::PendingHTLCsForwardable { .. } => { },
7935 _ => panic!("Unexpected event"),
7938 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
7939 nodes[2].node.process_pending_htlc_forwards();
7941 let events_6 = nodes[2].node.get_and_clear_pending_events();
7942 assert_eq!(events_6.len(), 1);
7944 Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
7945 _ => panic!("Unexpected event"),
7948 if test_ignore_second_cs {
7949 let events_7 = nodes[1].node.get_and_clear_pending_events();
7950 assert_eq!(events_7.len(), 1);
7952 Event::PendingHTLCsForwardable { .. } => { },
7953 _ => panic!("Unexpected event"),
7956 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7957 nodes[1].node.process_pending_htlc_forwards();
7958 check_added_monitors!(nodes[1], 1);
7960 send_event = SendEvent::from_node(&nodes[1]);
7961 assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
7962 assert_eq!(send_event.msgs.len(), 1);
7963 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7964 commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
7966 let events_8 = nodes[0].node.get_and_clear_pending_events();
7967 assert_eq!(events_8.len(), 1);
7969 Event::PendingHTLCsForwardable { .. } => { },
7970 _ => panic!("Unexpected event"),
7973 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
7974 nodes[0].node.process_pending_htlc_forwards();
7976 let events_9 = nodes[0].node.get_and_clear_pending_events();
7977 assert_eq!(events_9.len(), 1);
7979 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
7980 _ => panic!("Unexpected event"),
7982 claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
7985 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
7989 fn test_monitor_update_fail_raa() {
7990 do_test_monitor_update_fail_raa(false);
7991 do_test_monitor_update_fail_raa(true);
7995 fn test_monitor_update_fail_reestablish() {
7996 // Simple test for message retransmission after monitor update failure on
7997 // channel_reestablish generating a monitor update (which comes from freeing holding cell
7999 let mut nodes = create_network(3);
8000 create_announced_chan_between_nodes(&nodes, 0, 1);
8001 create_announced_chan_between_nodes(&nodes, 1, 2);
8003 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8005 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8006 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8008 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8009 check_added_monitors!(nodes[2], 1);
8010 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8011 assert!(updates.update_add_htlcs.is_empty());
8012 assert!(updates.update_fail_htlcs.is_empty());
8013 assert!(updates.update_fail_malformed_htlcs.is_empty());
8014 assert!(updates.update_fee.is_none());
8015 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8016 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8017 check_added_monitors!(nodes[1], 1);
8018 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8019 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8021 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8022 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8023 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8025 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8026 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8028 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8030 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap_err() {
8031 assert_eq!(err, "Failed to update ChannelMonitor");
8032 } else { panic!(); }
8033 check_added_monitors!(nodes[1], 1);
8035 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8036 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8038 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8039 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8041 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8042 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8044 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8046 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8047 check_added_monitors!(nodes[1], 0);
8048 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8050 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8051 nodes[1].node.test_restore_channel_monitor();
8052 check_added_monitors!(nodes[1], 1);
8054 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8055 assert!(updates.update_add_htlcs.is_empty());
8056 assert!(updates.update_fail_htlcs.is_empty());
8057 assert!(updates.update_fail_malformed_htlcs.is_empty());
8058 assert!(updates.update_fee.is_none());
8059 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8060 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8061 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8063 let events = nodes[0].node.get_and_clear_pending_events();
8064 assert_eq!(events.len(), 1);
8066 Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8067 _ => panic!("Unexpected event"),
8072 fn test_invalid_channel_announcement() {
8073 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8074 let secp_ctx = Secp256k1::new();
8075 let nodes = create_network(2);
8077 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8079 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8080 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8081 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8082 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8084 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 } );
8086 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8087 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8089 let as_network_key = nodes[0].node.get_our_node_id();
8090 let bs_network_key = nodes[1].node.get_our_node_id();
8092 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8094 let mut chan_announcement;
8096 macro_rules! dummy_unsigned_msg {
8098 msgs::UnsignedChannelAnnouncement {
8099 features: msgs::GlobalFeatures::new(),
8100 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8101 short_channel_id: as_chan.get_short_channel_id().unwrap(),
8102 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8103 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8104 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8105 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8106 excess_data: Vec::new(),
8111 macro_rules! sign_msg {
8112 ($unsigned_msg: expr) => {
8113 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8114 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8115 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8116 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8117 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8118 chan_announcement = msgs::ChannelAnnouncement {
8119 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8120 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8121 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8122 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8123 contents: $unsigned_msg
8128 let unsigned_msg = dummy_unsigned_msg!();
8129 sign_msg!(unsigned_msg);
8130 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8131 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 } );
8133 // Configured with Network::Testnet
8134 let mut unsigned_msg = dummy_unsigned_msg!();
8135 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8136 sign_msg!(unsigned_msg);
8137 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8139 let mut unsigned_msg = dummy_unsigned_msg!();
8140 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8141 sign_msg!(unsigned_msg);
8142 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8145 struct VecWriter(Vec<u8>);
8146 impl Writer for VecWriter {
8147 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8148 self.0.extend_from_slice(buf);
8151 fn size_hint(&mut self, size: usize) {
8152 self.0.reserve_exact(size);
8157 fn test_no_txn_manager_serialize_deserialize() {
8158 let mut nodes = create_network(2);
8160 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8162 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8164 let nodes_0_serialized = nodes[0].node.encode();
8165 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8166 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8168 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
8169 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8170 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8171 assert!(chan_0_monitor_read.is_empty());
8173 let mut nodes_0_read = &nodes_0_serialized[..];
8174 let config = UserConfig::new();
8175 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8176 let (_, nodes_0_deserialized) = {
8177 let mut channel_monitors = HashMap::new();
8178 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8179 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8180 default_config: config,
8182 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8183 monitor: nodes[0].chan_monitor.clone(),
8184 chain_monitor: nodes[0].chain_monitor.clone(),
8185 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8186 logger: Arc::new(test_utils::TestLogger::new()),
8187 channel_monitors: &channel_monitors,
8190 assert!(nodes_0_read.is_empty());
8192 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8193 nodes[0].node = Arc::new(nodes_0_deserialized);
8194 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8195 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8196 assert_eq!(nodes[0].node.list_channels().len(), 1);
8197 check_added_monitors!(nodes[0], 1);
8199 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8200 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8201 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8202 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8204 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8205 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8206 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8207 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8209 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8210 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8211 for node in nodes.iter() {
8212 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8213 node.router.handle_channel_update(&as_update).unwrap();
8214 node.router.handle_channel_update(&bs_update).unwrap();
8217 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8221 fn test_simple_manager_serialize_deserialize() {
8222 let mut nodes = create_network(2);
8223 create_announced_chan_between_nodes(&nodes, 0, 1);
8225 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8226 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8228 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8230 let nodes_0_serialized = nodes[0].node.encode();
8231 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8232 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8234 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
8235 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8236 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8237 assert!(chan_0_monitor_read.is_empty());
8239 let mut nodes_0_read = &nodes_0_serialized[..];
8240 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8241 let (_, nodes_0_deserialized) = {
8242 let mut channel_monitors = HashMap::new();
8243 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8244 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8245 default_config: UserConfig::new(),
8247 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8248 monitor: nodes[0].chan_monitor.clone(),
8249 chain_monitor: nodes[0].chain_monitor.clone(),
8250 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8251 logger: Arc::new(test_utils::TestLogger::new()),
8252 channel_monitors: &channel_monitors,
8255 assert!(nodes_0_read.is_empty());
8257 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8258 nodes[0].node = Arc::new(nodes_0_deserialized);
8259 check_added_monitors!(nodes[0], 1);
8261 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8263 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8264 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8268 fn test_manager_serialize_deserialize_inconsistent_monitor() {
8269 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8270 let mut nodes = create_network(4);
8271 create_announced_chan_between_nodes(&nodes, 0, 1);
8272 create_announced_chan_between_nodes(&nodes, 2, 0);
8273 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8275 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8277 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8278 let nodes_0_serialized = nodes[0].node.encode();
8280 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8281 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8282 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8283 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8285 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8287 let mut node_0_monitors_serialized = Vec::new();
8288 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8289 let mut writer = VecWriter(Vec::new());
8290 monitor.1.write_for_disk(&mut writer).unwrap();
8291 node_0_monitors_serialized.push(writer.0);
8294 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
8295 let mut node_0_monitors = Vec::new();
8296 for serialized in node_0_monitors_serialized.iter() {
8297 let mut read = &serialized[..];
8298 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8299 assert!(read.is_empty());
8300 node_0_monitors.push(monitor);
8303 let mut nodes_0_read = &nodes_0_serialized[..];
8304 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8305 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8306 default_config: UserConfig::new(),
8308 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8309 monitor: nodes[0].chan_monitor.clone(),
8310 chain_monitor: nodes[0].chain_monitor.clone(),
8311 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8312 logger: Arc::new(test_utils::TestLogger::new()),
8313 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8315 assert!(nodes_0_read.is_empty());
8317 { // Channel close should result in a commitment tx and an HTLC tx
8318 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8319 assert_eq!(txn.len(), 2);
8320 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8321 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8324 for monitor in node_0_monitors.drain(..) {
8325 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8326 check_added_monitors!(nodes[0], 1);
8328 nodes[0].node = Arc::new(nodes_0_deserialized);
8330 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8331 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8332 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8333 //... and we can even still claim the payment!
8334 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8336 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8337 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8338 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8339 if let Err(msgs::HandleError { action: Some(msgs::ErrorAction::SendErrorMessage { msg }), .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
8340 assert_eq!(msg.channel_id, channel_id);
8341 } else { panic!("Unexpected result"); }
8344 macro_rules! check_spendable_outputs {
8345 ($node: expr, $der_idx: expr) => {
8347 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8348 let mut txn = Vec::new();
8349 for event in events {
8351 Event::SpendableOutputs { ref outputs } => {
8352 for outp in outputs {
8354 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8356 previous_output: outpoint.clone(),
8357 script_sig: Script::new(),
8359 witness: Vec::new(),
8362 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8363 value: output.value,
8365 let mut spend_tx = Transaction {
8371 let secp_ctx = Secp256k1::new();
8372 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8373 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8374 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8375 let remotesig = secp_ctx.sign(&sighash, key);
8376 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8377 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8378 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8381 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8383 previous_output: outpoint.clone(),
8384 script_sig: Script::new(),
8385 sequence: *to_self_delay as u32,
8386 witness: Vec::new(),
8389 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8390 value: output.value,
8392 let mut spend_tx = Transaction {
8398 let secp_ctx = Secp256k1::new();
8399 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8400 let local_delaysig = secp_ctx.sign(&sighash, key);
8401 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8402 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8403 spend_tx.input[0].witness.push(vec!(0));
8404 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8407 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8408 let secp_ctx = Secp256k1::new();
8410 previous_output: outpoint.clone(),
8411 script_sig: Script::new(),
8413 witness: Vec::new(),
8416 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8417 value: output.value,
8419 let mut spend_tx = Transaction {
8423 output: vec![outp.clone()],
8426 match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8428 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8430 Err(_) => panic!("Your RNG is busted"),
8433 Err(_) => panic!("Your rng is busted"),
8436 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8437 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8438 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8439 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8440 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8441 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8442 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8448 _ => panic!("Unexpected event"),
8457 fn test_claim_sizeable_push_msat() {
8458 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8459 let nodes = create_network(2);
8461 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8462 nodes[1].node.force_close_channel(&chan.2);
8463 let events = nodes[1].node.get_and_clear_pending_msg_events();
8465 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8466 _ => panic!("Unexpected event"),
8468 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8469 assert_eq!(node_txn.len(), 1);
8470 check_spends!(node_txn[0], chan.3.clone());
8471 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
8473 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8474 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8475 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8476 assert_eq!(spend_txn.len(), 1);
8477 check_spends!(spend_txn[0], node_txn[0].clone());
8481 fn test_claim_on_remote_sizeable_push_msat() {
8482 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8483 // to_remote output is encumbered by a P2WPKH
8485 let nodes = create_network(2);
8487 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8488 nodes[0].node.force_close_channel(&chan.2);
8489 let events = nodes[0].node.get_and_clear_pending_msg_events();
8491 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8492 _ => panic!("Unexpected event"),
8494 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8495 assert_eq!(node_txn.len(), 1);
8496 check_spends!(node_txn[0], chan.3.clone());
8497 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
8499 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8500 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8501 let events = nodes[1].node.get_and_clear_pending_msg_events();
8503 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8504 _ => panic!("Unexpected event"),
8506 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8507 assert_eq!(spend_txn.len(), 2);
8508 assert_eq!(spend_txn[0], spend_txn[1]);
8509 check_spends!(spend_txn[0], node_txn[0].clone());
8513 fn test_claim_on_remote_revoked_sizeable_push_msat() {
8514 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8515 // to_remote output is encumbered by a P2WPKH
8517 let nodes = create_network(2);
8519 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8520 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8521 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8522 assert_eq!(revoked_local_txn[0].input.len(), 1);
8523 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8525 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8526 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8527 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8528 let events = nodes[1].node.get_and_clear_pending_msg_events();
8530 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8531 _ => panic!("Unexpected event"),
8533 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8534 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8535 assert_eq!(spend_txn.len(), 4);
8536 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8537 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8538 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8539 check_spends!(spend_txn[1], node_txn[0].clone());
8543 fn test_static_spendable_outputs_preimage_tx() {
8544 let nodes = create_network(2);
8546 // Create some initial channels
8547 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8549 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8551 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8552 assert_eq!(commitment_tx[0].input.len(), 1);
8553 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8555 // Settle A's commitment tx on B's chain
8556 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8557 assert!(nodes[1].node.claim_funds(payment_preimage));
8558 check_added_monitors!(nodes[1], 1);
8559 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8560 let events = nodes[1].node.get_and_clear_pending_msg_events();
8562 MessageSendEvent::UpdateHTLCs { .. } => {},
8563 _ => panic!("Unexpected event"),
8566 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8567 _ => panic!("Unexepected event"),
8570 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8571 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8572 check_spends!(node_txn[0], commitment_tx[0].clone());
8573 assert_eq!(node_txn[0], node_txn[2]);
8574 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8575 check_spends!(node_txn[1], chan_1.3.clone());
8577 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8578 assert_eq!(spend_txn.len(), 2);
8579 assert_eq!(spend_txn[0], spend_txn[1]);
8580 check_spends!(spend_txn[0], node_txn[0].clone());
8584 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8585 let nodes = create_network(2);
8587 // Create some initial channels
8588 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8590 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8591 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8592 assert_eq!(revoked_local_txn[0].input.len(), 1);
8593 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8595 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8597 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8598 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8599 let events = nodes[1].node.get_and_clear_pending_msg_events();
8601 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8602 _ => panic!("Unexpected event"),
8604 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8605 assert_eq!(node_txn.len(), 3);
8606 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
8607 assert_eq!(node_txn[0].input.len(), 2);
8608 check_spends!(node_txn[0], revoked_local_txn[0].clone());
8610 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8611 assert_eq!(spend_txn.len(), 2);
8612 assert_eq!(spend_txn[0], spend_txn[1]);
8613 check_spends!(spend_txn[0], node_txn[0].clone());
8617 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
8618 let nodes = create_network(2);
8620 // Create some initial channels
8621 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8623 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8624 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8625 assert_eq!(revoked_local_txn[0].input.len(), 1);
8626 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8628 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8630 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8631 // A will generate HTLC-Timeout from revoked commitment tx
8632 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8633 let events = nodes[0].node.get_and_clear_pending_msg_events();
8635 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8636 _ => panic!("Unexpected event"),
8638 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8639 assert_eq!(revoked_htlc_txn.len(), 3);
8640 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
8641 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8642 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8643 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8644 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
8646 // B will generate justice tx from A's revoked commitment/HTLC tx
8647 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8648 let events = nodes[1].node.get_and_clear_pending_msg_events();
8650 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8651 _ => panic!("Unexpected event"),
8654 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8655 assert_eq!(node_txn.len(), 4);
8656 assert_eq!(node_txn[3].input.len(), 1);
8657 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8659 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
8660 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8661 assert_eq!(spend_txn.len(), 3);
8662 assert_eq!(spend_txn[0], spend_txn[1]);
8663 check_spends!(spend_txn[0], node_txn[0].clone());
8664 check_spends!(spend_txn[2], node_txn[3].clone());
8668 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
8669 let nodes = create_network(2);
8671 // Create some initial channels
8672 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8674 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8675 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8676 assert_eq!(revoked_local_txn[0].input.len(), 1);
8677 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8679 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8681 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8682 // B will generate HTLC-Success from revoked commitment tx
8683 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8684 let events = nodes[1].node.get_and_clear_pending_msg_events();
8686 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8687 _ => panic!("Unexpected event"),
8689 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8691 assert_eq!(revoked_htlc_txn.len(), 3);
8692 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
8693 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8694 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8695 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8697 // A will generate justice tx from B's revoked commitment/HTLC tx
8698 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8699 let events = nodes[0].node.get_and_clear_pending_msg_events();
8701 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8702 _ => panic!("Unexpected event"),
8705 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8706 assert_eq!(node_txn.len(), 4);
8707 assert_eq!(node_txn[3].input.len(), 1);
8708 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8710 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
8711 let spend_txn = check_spendable_outputs!(nodes[0], 1);
8712 assert_eq!(spend_txn.len(), 5);
8713 assert_eq!(spend_txn[0], spend_txn[2]);
8714 assert_eq!(spend_txn[1], spend_txn[3]);
8715 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
8716 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
8717 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
8721 fn test_onchain_to_onchain_claim() {
8722 // Test that in case of channel closure, we detect the state of output thanks to
8723 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
8724 // First, have C claim an HTLC against its own latest commitment transaction.
8725 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
8727 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
8730 let nodes = create_network(3);
8732 // Create some initial channels
8733 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8734 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8736 // Rebalance the network a bit by relaying one payment through all the channels ...
8737 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
8738 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
8740 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
8741 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8742 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
8743 check_spends!(commitment_tx[0], chan_2.3.clone());
8744 nodes[2].node.claim_funds(payment_preimage);
8745 check_added_monitors!(nodes[2], 1);
8746 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8747 assert!(updates.update_add_htlcs.is_empty());
8748 assert!(updates.update_fail_htlcs.is_empty());
8749 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8750 assert!(updates.update_fail_malformed_htlcs.is_empty());
8752 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
8753 let events = nodes[2].node.get_and_clear_pending_msg_events();
8754 assert_eq!(events.len(), 1);
8756 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8757 _ => panic!("Unexpected event"),
8760 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
8761 assert_eq!(c_txn.len(), 3);
8762 assert_eq!(c_txn[0], c_txn[2]);
8763 assert_eq!(commitment_tx[0], c_txn[1]);
8764 check_spends!(c_txn[1], chan_2.3.clone());
8765 check_spends!(c_txn[2], c_txn[1].clone());
8766 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
8767 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8768 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
8769 assert_eq!(c_txn[0].lock_time, 0); // Success tx
8771 // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
8772 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
8774 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8775 assert_eq!(b_txn.len(), 4);
8776 assert_eq!(b_txn[0], b_txn[3]);
8777 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
8778 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
8779 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8780 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
8781 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
8782 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
8783 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8784 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
8785 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
8788 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
8789 check_added_monitors!(nodes[1], 1);
8790 match msg_events[0] {
8791 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8792 _ => panic!("Unexpected event"),
8794 match msg_events[1] {
8795 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
8796 assert!(update_add_htlcs.is_empty());
8797 assert!(update_fail_htlcs.is_empty());
8798 assert_eq!(update_fulfill_htlcs.len(), 1);
8799 assert!(update_fail_malformed_htlcs.is_empty());
8800 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
8802 _ => panic!("Unexpected event"),
8804 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
8805 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8806 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
8807 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8808 assert_eq!(b_txn.len(), 3);
8809 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
8810 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
8811 check_spends!(b_txn[0], commitment_tx[0].clone());
8812 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8813 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
8814 assert_eq!(b_txn[2].lock_time, 0); // Success tx
8815 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
8816 match msg_events[0] {
8817 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8818 _ => panic!("Unexpected event"),
8823 fn test_duplicate_payment_hash_one_failure_one_success() {
8824 // Topology : A --> B --> C
8825 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
8826 let mut nodes = create_network(3);
8828 create_announced_chan_between_nodes(&nodes, 0, 1);
8829 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8831 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
8832 *nodes[0].network_payment_count.borrow_mut() -= 1;
8833 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
8835 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
8836 assert_eq!(commitment_txn[0].input.len(), 1);
8837 check_spends!(commitment_txn[0], chan_2.3.clone());
8839 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8840 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
8841 let htlc_timeout_tx;
8842 { // Extract one of the two HTLC-Timeout transaction
8843 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8844 assert_eq!(node_txn.len(), 7);
8845 assert_eq!(node_txn[0], node_txn[5]);
8846 assert_eq!(node_txn[1], node_txn[6]);
8847 check_spends!(node_txn[0], commitment_txn[0].clone());
8848 assert_eq!(node_txn[0].input.len(), 1);
8849 check_spends!(node_txn[1], commitment_txn[0].clone());
8850 assert_eq!(node_txn[1].input.len(), 1);
8851 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
8852 check_spends!(node_txn[2], chan_2.3.clone());
8853 check_spends!(node_txn[3], node_txn[2].clone());
8854 check_spends!(node_txn[4], node_txn[2].clone());
8855 htlc_timeout_tx = node_txn[1].clone();
8858 let events = nodes[1].node.get_and_clear_pending_msg_events();
8860 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8861 _ => panic!("Unexepected event"),
8864 nodes[2].node.claim_funds(our_payment_preimage);
8865 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
8866 check_added_monitors!(nodes[2], 2);
8867 let events = nodes[2].node.get_and_clear_pending_msg_events();
8869 MessageSendEvent::UpdateHTLCs { .. } => {},
8870 _ => panic!("Unexpected event"),
8873 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8874 _ => panic!("Unexepected event"),
8876 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8877 assert_eq!(htlc_success_txn.len(), 5);
8878 check_spends!(htlc_success_txn[2], chan_2.3.clone());
8879 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
8880 assert_eq!(htlc_success_txn[0].input.len(), 1);
8881 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8882 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
8883 assert_eq!(htlc_success_txn[1].input.len(), 1);
8884 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8885 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
8886 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
8887 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
8889 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
8890 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8891 assert!(htlc_updates.update_add_htlcs.is_empty());
8892 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
8893 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
8894 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
8895 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
8896 check_added_monitors!(nodes[1], 1);
8898 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
8899 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8901 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
8902 let events = nodes[0].node.get_and_clear_pending_msg_events();
8903 assert_eq!(events.len(), 1);
8905 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
8907 _ => { panic!("Unexpected event"); }
8910 let events = nodes[0].node.get_and_clear_pending_events();
8912 Event::PaymentFailed { ref payment_hash, .. } => {
8913 assert_eq!(*payment_hash, duplicate_payment_hash);
8915 _ => panic!("Unexpected event"),
8918 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
8919 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
8920 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8921 assert!(updates.update_add_htlcs.is_empty());
8922 assert!(updates.update_fail_htlcs.is_empty());
8923 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8924 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
8925 assert!(updates.update_fail_malformed_htlcs.is_empty());
8926 check_added_monitors!(nodes[1], 1);
8928 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8929 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
8931 let events = nodes[0].node.get_and_clear_pending_events();
8933 Event::PaymentSent { ref payment_preimage } => {
8934 assert_eq!(*payment_preimage, our_payment_preimage);
8936 _ => panic!("Unexpected event"),
8941 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
8942 let nodes = create_network(2);
8944 // Create some initial channels
8945 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8947 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8948 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8949 assert_eq!(local_txn[0].input.len(), 1);
8950 check_spends!(local_txn[0], chan_1.3.clone());
8952 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
8953 nodes[1].node.claim_funds(payment_preimage);
8954 check_added_monitors!(nodes[1], 1);
8955 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8956 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
8957 let events = nodes[1].node.get_and_clear_pending_msg_events();
8959 MessageSendEvent::UpdateHTLCs { .. } => {},
8960 _ => panic!("Unexpected event"),
8963 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8964 _ => panic!("Unexepected event"),
8966 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8967 assert_eq!(node_txn[0].input.len(), 1);
8968 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8969 check_spends!(node_txn[0], local_txn[0].clone());
8971 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
8972 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8973 assert_eq!(spend_txn.len(), 2);
8974 check_spends!(spend_txn[0], node_txn[0].clone());
8975 check_spends!(spend_txn[1], node_txn[2].clone());
8979 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
8980 let nodes = create_network(2);
8982 // Create some initial channels
8983 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8985 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8986 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8987 assert_eq!(local_txn[0].input.len(), 1);
8988 check_spends!(local_txn[0], chan_1.3.clone());
8990 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8991 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8992 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8993 let events = nodes[0].node.get_and_clear_pending_msg_events();
8995 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8996 _ => panic!("Unexepected event"),
8998 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8999 assert_eq!(node_txn[0].input.len(), 1);
9000 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9001 check_spends!(node_txn[0], local_txn[0].clone());
9003 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9004 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9005 assert_eq!(spend_txn.len(), 8);
9006 assert_eq!(spend_txn[0], spend_txn[2]);
9007 assert_eq!(spend_txn[0], spend_txn[4]);
9008 assert_eq!(spend_txn[0], spend_txn[6]);
9009 assert_eq!(spend_txn[1], spend_txn[3]);
9010 assert_eq!(spend_txn[1], spend_txn[5]);
9011 assert_eq!(spend_txn[1], spend_txn[7]);
9012 check_spends!(spend_txn[0], local_txn[0].clone());
9013 check_spends!(spend_txn[1], node_txn[0].clone());
9017 fn test_static_output_closing_tx() {
9018 let nodes = create_network(2);
9020 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9022 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9023 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9025 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9026 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9027 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9028 assert_eq!(spend_txn.len(), 1);
9029 check_spends!(spend_txn[0], closing_tx.clone());
9031 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9032 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9033 assert_eq!(spend_txn.len(), 1);
9034 check_spends!(spend_txn[0], closing_tx);
9037 fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
9038 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9041 run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
9045 // 0: node1 fail backward
9046 // 1: final node fail backward
9047 // 2: payment completed but the user reject the payment
9048 // 3: final node fail backward (but tamper onion payloads from node0)
9049 // 100: trigger error in the intermediate node and tamper returnning fail_htlc
9050 // 200: trigger error in the final node and tamper returnning fail_htlc
9051 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
9052 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9053 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
9056 use ln::msgs::HTLCFailChannelUpdate;
9058 // reset block height
9059 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9060 for ix in 0..nodes.len() {
9061 nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
9064 macro_rules! expect_event {
9065 ($node: expr, $event_type: path) => {{
9066 let events = $node.node.get_and_clear_pending_events();
9067 assert_eq!(events.len(), 1);
9069 $event_type { .. } => {},
9070 _ => panic!("Unexpected event"),
9075 macro_rules! expect_htlc_forward {
9077 expect_event!($node, Event::PendingHTLCsForwardable);
9078 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
9079 $node.node.process_pending_htlc_forwards();
9083 // 0 ~~> 2 send payment
9084 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
9085 check_added_monitors!(nodes[0], 1);
9086 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9087 // temper update_add (0 => 1)
9088 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
9089 if test_case == 0 || test_case == 3 || test_case == 100 {
9090 callback_msg(&mut update_add_0);
9093 // 0 => 1 update_add & CS
9094 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
9095 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
9097 let update_1_0 = match test_case {
9098 0|100 => { // intermediate node failure; fail backward to 0
9099 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9100 assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
9103 1|2|3|200 => { // final node failure; forwarding to 2
9104 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9106 if test_case != 200 {
9109 expect_htlc_forward!(&nodes[1]);
9111 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
9112 check_added_monitors!(&nodes[1], 1);
9113 assert_eq!(update_1.update_add_htlcs.len(), 1);
9114 // tamper update_add (1 => 2)
9115 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
9116 if test_case != 3 && test_case != 200 {
9117 callback_msg(&mut update_add_1);
9121 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
9122 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
9124 if test_case == 2 || test_case == 200 {
9125 expect_htlc_forward!(&nodes[2]);
9126 expect_event!(&nodes[2], Event::PaymentReceived);
9130 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9131 if test_case == 2 || test_case == 200 {
9132 check_added_monitors!(&nodes[2], 1);
9134 assert!(update_2_1.update_fail_htlcs.len() == 1);
9136 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
9137 if test_case == 200 {
9138 callback_fail(&mut fail_msg);
9142 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
9143 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true, true);
9145 // backward fail on 1
9146 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9147 assert!(update_1_0.update_fail_htlcs.len() == 1);
9150 _ => unreachable!(),
9153 // 1 => 0 commitment_signed_dance
9154 if update_1_0.update_fail_htlcs.len() > 0 {
9155 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
9156 if test_case == 100 {
9157 callback_fail(&mut fail_msg);
9159 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
9161 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
9164 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
9166 let events = nodes[0].node.get_and_clear_pending_events();
9167 assert_eq!(events.len(), 1);
9168 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
9169 assert_eq!(*rejected_by_dest, !expected_retryable);
9170 assert_eq!(*error_code, expected_error_code);
9172 panic!("Uexpected event");
9175 let events = nodes[0].node.get_and_clear_pending_msg_events();
9176 if expected_channel_update.is_some() {
9177 assert_eq!(events.len(), 1);
9179 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
9181 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
9182 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
9183 panic!("channel_update not found!");
9186 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
9187 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9188 assert!(*short_channel_id == *expected_short_channel_id);
9189 assert!(*is_permanent == *expected_is_permanent);
9191 panic!("Unexpected message event");
9194 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
9195 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9196 assert!(*node_id == *expected_node_id);
9197 assert!(*is_permanent == *expected_is_permanent);
9199 panic!("Unexpected message event");
9204 _ => panic!("Unexpected message event"),
9207 assert_eq!(events.len(), 0);
9211 impl msgs::ChannelUpdate {
9212 fn dummy() -> msgs::ChannelUpdate {
9213 use secp256k1::ffi::Signature as FFISignature;
9214 use secp256k1::Signature;
9215 msgs::ChannelUpdate {
9216 signature: Signature::from(FFISignature::new()),
9217 contents: msgs::UnsignedChannelUpdate {
9218 chain_hash: Sha256dHash::from_data(&vec![0u8][..]),
9219 short_channel_id: 0,
9222 cltv_expiry_delta: 0,
9223 htlc_minimum_msat: 0,
9225 fee_proportional_millionths: 0,
9226 excess_data: vec![],
9233 fn test_onion_failure() {
9234 use ln::msgs::ChannelUpdate;
9235 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
9238 const BADONION: u16 = 0x8000;
9239 const PERM: u16 = 0x4000;
9240 const NODE: u16 = 0x2000;
9241 const UPDATE: u16 = 0x1000;
9243 let mut nodes = create_network(3);
9244 for node in nodes.iter() {
9245 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&Secp256k1::without_caps(), &[3; 32]).unwrap());
9247 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
9248 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
9249 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
9251 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
9253 // intermediate node failure
9254 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
9255 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9256 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9257 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9258 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
9259 onion_payloads[0].realm = 3;
9260 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9261 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
9263 // final node failure
9264 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
9265 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9266 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9267 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9268 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
9269 onion_payloads[1].realm = 3;
9270 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9271 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9273 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
9274 // receiving simulated fail messages
9275 // intermediate node failure
9276 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9278 msg.amount_msat -= 1;
9280 // and tamper returing error message
9281 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9282 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9283 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
9284 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
9286 // final node failure
9287 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9288 // and tamper returing error message
9289 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9290 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9291 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
9293 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9294 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
9296 // intermediate node failure
9297 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9298 msg.amount_msat -= 1;
9300 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9301 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9302 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
9303 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9305 // final node failure
9306 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9307 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9308 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9309 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
9311 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9312 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9314 // intermediate node failure
9315 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9316 msg.amount_msat -= 1;
9318 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9319 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9320 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
9322 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9323 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9325 // final node failure
9326 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9327 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9328 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9329 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
9331 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9332 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9334 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
9335 Some(BADONION|PERM|4), None);
9337 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
9338 Some(BADONION|PERM|5), None);
9340 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
9341 Some(BADONION|PERM|6), None);
9343 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9344 msg.amount_msat -= 1;
9346 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9347 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9348 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
9349 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9351 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9352 msg.amount_msat -= 1;
9354 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9355 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9356 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
9357 // short_channel_id from the processing node
9358 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9360 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9361 msg.amount_msat -= 1;
9363 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9364 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9365 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
9366 // short_channel_id from the processing node
9367 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9369 let mut bogus_route = route.clone();
9370 bogus_route.hops[1].short_channel_id -= 1;
9371 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
9372 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
9374 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
9375 let mut bogus_route = route.clone();
9376 let route_len = bogus_route.hops.len();
9377 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
9378 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9380 //TODO: with new config API, we will be able to generate both valid and
9381 //invalid channel_update cases.
9382 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
9383 msg.amount_msat -= 1;
9384 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9386 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
9387 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
9388 msg.cltv_expiry -= 1;
9389 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9391 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
9392 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9393 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9394 nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9395 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9397 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
9398 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9399 }, false, Some(PERM|15), None);
9401 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
9402 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9403 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9404 nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9405 }, || {}, true, Some(17), None);
9407 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
9408 for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9409 for f in pending_forwards.iter_mut() {
9410 f.forward_info.outgoing_cltv_value += 1;
9413 }, true, Some(18), None);
9415 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
9416 // violate amt_to_forward > msg.amount_msat
9417 for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9418 for f in pending_forwards.iter_mut() {
9419 f.forward_info.amt_to_forward -= 1;
9422 }, true, Some(19), None);
9424 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
9425 // disconnect event to the channel between nodes[1] ~ nodes[2]
9426 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9427 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9428 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9429 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9431 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
9432 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9433 let mut route = route.clone();
9435 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
9436 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9437 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
9438 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9439 msg.cltv_expiry = htlc_cltv;
9440 msg.onion_routing_packet = onion_packet;
9441 }, ||{}, true, Some(21), None);