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 secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
26 use ln::router::{Route,RouteHop};
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
39 use crypto::mac::{Mac,MacResult};
40 use crypto::hmac::Hmac;
41 use crypto::digest::Digest;
42 use crypto::symmetriccipher::SynchronousStreamCipher;
44 use std::{cmp, ptr, mem};
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 mod channel_held_info {
65 use ln::router::Route;
66 use ln::channelmanager::PaymentHash;
67 use secp256k1::key::SecretKey;
69 /// Stores the info we will need to send when we want to forward an HTLC onwards
70 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
71 pub struct PendingForwardHTLCInfo {
72 pub(super) onion_packet: Option<msgs::OnionPacket>,
73 pub(super) incoming_shared_secret: [u8; 32],
74 pub(super) payment_hash: PaymentHash,
75 pub(super) short_channel_id: u64,
76 pub(super) amt_to_forward: u64,
77 pub(super) outgoing_cltv_value: u32,
80 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81 pub enum HTLCFailureMsg {
82 Relay(msgs::UpdateFailHTLC),
83 Malformed(msgs::UpdateFailMalformedHTLC),
86 /// Stores whether we can't forward an HTLC or relevant forwarding info
87 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88 pub enum PendingHTLCStatus {
89 Forward(PendingForwardHTLCInfo),
93 /// Tracks the inbound corresponding to an outbound HTLC
94 #[derive(Clone, PartialEq)]
95 pub struct HTLCPreviousHopData {
96 pub(super) short_channel_id: u64,
97 pub(super) htlc_id: u64,
98 pub(super) incoming_packet_shared_secret: [u8; 32],
101 /// Tracks the inbound corresponding to an outbound HTLC
102 #[derive(Clone, PartialEq)]
103 pub enum HTLCSource {
104 PreviousHopData(HTLCPreviousHopData),
107 session_priv: SecretKey,
108 /// Technically we can recalculate this from the route, but we cache it here to avoid
109 /// doing a double-pass on route when we get a failure back
110 first_hop_htlc_msat: u64,
115 pub fn dummy() -> Self {
116 HTLCSource::OutboundRoute {
117 route: Route { hops: Vec::new() },
118 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
119 first_hop_htlc_msat: 0,
124 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125 pub(crate) enum HTLCFailReason {
127 err: msgs::OnionErrorPacket,
135 pub(super) use self::channel_held_info::*;
137 /// payment_hash type, use to cross-lock hop
138 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
139 pub struct PaymentHash(pub [u8;32]);
140 /// payment_preimage type, use to route payment between hop
141 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
142 pub struct PaymentPreimage(pub [u8;32]);
144 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
146 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
147 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
148 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
149 /// channel_state lock. We then return the set of things that need to be done outside the lock in
150 /// this struct and call handle_error!() on it.
152 struct MsgHandleErrInternal {
153 err: msgs::HandleError,
154 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
156 impl MsgHandleErrInternal {
158 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
162 action: Some(msgs::ErrorAction::SendErrorMessage {
163 msg: msgs::ErrorMessage {
165 data: err.to_string()
169 shutdown_finish: None,
173 fn from_no_close(err: msgs::HandleError) -> Self {
174 Self { err, shutdown_finish: None }
177 fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
181 action: Some(msgs::ErrorAction::SendErrorMessage {
182 msg: msgs::ErrorMessage {
184 data: err.to_string()
188 shutdown_finish: Some((shutdown_res, channel_update)),
192 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
195 ChannelError::Ignore(msg) => HandleError {
197 action: Some(msgs::ErrorAction::IgnoreError),
199 ChannelError::Close(msg) => HandleError {
201 action: Some(msgs::ErrorAction::SendErrorMessage {
202 msg: msgs::ErrorMessage {
204 data: msg.to_string()
209 shutdown_finish: None,
214 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
215 /// after a PaymentReceived event.
217 pub enum PaymentFailReason {
218 /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
220 /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
224 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
225 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
226 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
227 /// probably increase this significantly.
228 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
230 struct HTLCForwardInfo {
231 prev_short_channel_id: u64,
233 forward_info: PendingForwardHTLCInfo,
236 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
237 /// be sent in the order they appear in the return value, however sometimes the order needs to be
238 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
239 /// they were originally sent). In those cases, this enum is also returned.
240 #[derive(Clone, PartialEq)]
241 pub(super) enum RAACommitmentOrder {
242 /// Send the CommitmentUpdate messages first
244 /// Send the RevokeAndACK message first
248 struct ChannelHolder {
249 by_id: HashMap<[u8; 32], Channel>,
250 short_to_id: HashMap<u64, [u8; 32]>,
251 next_forward: Instant,
252 /// short channel id -> forward infos. Key of 0 means payments received
253 /// Note that while this is held in the same mutex as the channels themselves, no consistency
254 /// guarantees are made about there existing a channel with the short id here, nor the short
255 /// ids in the PendingForwardHTLCInfo!
256 forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
257 /// Note that while this is held in the same mutex as the channels themselves, no consistency
258 /// guarantees are made about the channels given here actually existing anymore by the time you
260 claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
261 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
262 /// for broadcast messages, where ordering isn't as strict).
263 pending_msg_events: Vec<events::MessageSendEvent>,
265 struct MutChannelHolder<'a> {
266 by_id: &'a mut HashMap<[u8; 32], Channel>,
267 short_to_id: &'a mut HashMap<u64, [u8; 32]>,
268 next_forward: &'a mut Instant,
269 forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
270 claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
271 pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
274 fn borrow_parts(&mut self) -> MutChannelHolder {
276 by_id: &mut self.by_id,
277 short_to_id: &mut self.short_to_id,
278 next_forward: &mut self.next_forward,
279 forward_htlcs: &mut self.forward_htlcs,
280 claimable_htlcs: &mut self.claimable_htlcs,
281 pending_msg_events: &mut self.pending_msg_events,
286 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
287 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
289 /// Manager which keeps track of a number of channels and sends messages to the appropriate
290 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
292 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
293 /// to individual Channels.
295 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
296 /// all peers during write/read (though does not modify this instance, only the instance being
297 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
298 /// called funding_transaction_generated for outbound channels).
300 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
301 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
302 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
303 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
304 /// the serialization process). If the deserialized version is out-of-date compared to the
305 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
306 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
308 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
309 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
310 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
311 /// block_connected() to step towards your best block) upon deserialization before using the
313 pub struct ChannelManager {
314 default_configuration: UserConfig,
315 genesis_hash: Sha256dHash,
316 fee_estimator: Arc<FeeEstimator>,
317 monitor: Arc<ManyChannelMonitor>,
318 chain_monitor: Arc<ChainWatchInterface>,
319 tx_broadcaster: Arc<BroadcasterInterface>,
321 latest_block_height: AtomicUsize,
322 last_block_hash: Mutex<Sha256dHash>,
323 secp_ctx: Secp256k1<secp256k1::All>,
325 channel_state: Mutex<ChannelHolder>,
326 our_network_key: SecretKey,
328 pending_events: Mutex<Vec<events::Event>>,
329 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
330 /// Essentially just when we're serializing ourselves out.
331 /// Taken first everywhere where we are making changes before any other locks.
332 total_consistency_lock: RwLock<()>,
334 keys_manager: Arc<KeysInterface>,
339 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
340 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
341 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
342 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
343 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
344 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
345 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
347 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
348 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
349 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
350 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
353 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
355 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
356 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
359 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
361 macro_rules! secp_call {
362 ( $res: expr, $err: expr ) => {
365 Err(_) => return Err($err),
372 shared_secret: SharedSecret,
374 blinding_factor: [u8; 32],
375 ephemeral_pubkey: PublicKey,
380 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
381 pub struct ChannelDetails {
382 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
383 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
384 /// Note that this means this value is *not* persistent - it can change once during the
385 /// lifetime of the channel.
386 pub channel_id: [u8; 32],
387 /// The position of the funding transaction in the chain. None if the funding transaction has
388 /// not yet been confirmed and the channel fully opened.
389 pub short_channel_id: Option<u64>,
390 /// The node_id of our counterparty
391 pub remote_network_id: PublicKey,
392 /// The value, in satoshis, of this channel as appears in the funding output
393 pub channel_value_satoshis: u64,
394 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
398 macro_rules! handle_error {
399 ($self: ident, $internal: expr, $their_node_id: expr) => {
402 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
403 if let Some((shutdown_res, update_option)) = shutdown_finish {
404 $self.finish_force_close_channel(shutdown_res);
405 if let Some(update) = update_option {
406 let mut channel_state = $self.channel_state.lock().unwrap();
407 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
418 macro_rules! break_chan_entry {
419 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
422 Err(ChannelError::Ignore(msg)) => {
423 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
425 Err(ChannelError::Close(msg)) => {
426 let (channel_id, mut chan) = $entry.remove_entry();
427 if let Some(short_id) = chan.get_short_channel_id() {
428 $channel_state.short_to_id.remove(&short_id);
430 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
436 macro_rules! try_chan_entry {
437 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
440 Err(ChannelError::Ignore(msg)) => {
441 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
443 Err(ChannelError::Close(msg)) => {
444 let (channel_id, mut chan) = $entry.remove_entry();
445 if let Some(short_id) = chan.get_short_channel_id() {
446 $channel_state.short_to_id.remove(&short_id);
448 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
454 macro_rules! return_monitor_err {
455 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
456 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
458 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
459 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
460 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
462 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
463 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
465 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
467 ChannelMonitorUpdateErr::PermanentFailure => {
468 let (channel_id, mut chan) = $entry.remove_entry();
469 if let Some(short_id) = chan.get_short_channel_id() {
470 $channel_state.short_to_id.remove(&short_id);
472 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
473 // chain in a confused state! We need to move them into the ChannelMonitor which
474 // will be responsible for failing backwards once things confirm on-chain.
475 // It's ok that we drop $failed_forwards here - at this point we'd rather they
476 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
477 // us bother trying to claim it just to forward on to another peer. If we're
478 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
479 // given up the preimage yet, so might as well just wait until the payment is
480 // retried, avoiding the on-chain fees.
481 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
483 ChannelMonitorUpdateErr::TemporaryFailure => {
484 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
485 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
491 // Does not break in case of TemporaryFailure!
492 macro_rules! maybe_break_monitor_err {
493 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
495 ChannelMonitorUpdateErr::PermanentFailure => {
496 let (channel_id, mut chan) = $entry.remove_entry();
497 if let Some(short_id) = chan.get_short_channel_id() {
498 $channel_state.short_to_id.remove(&short_id);
500 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
502 ChannelMonitorUpdateErr::TemporaryFailure => {
503 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
509 impl ChannelManager {
510 /// Constructs a new ChannelManager to hold several channels and route between them.
512 /// This is the main "logic hub" for all channel-related actions, and implements
513 /// ChannelMessageHandler.
515 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
517 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
518 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> {
519 let secp_ctx = Secp256k1::new();
521 let res = Arc::new(ChannelManager {
522 default_configuration: config.clone(),
523 genesis_hash: genesis_block(network).header.bitcoin_hash(),
524 fee_estimator: feeest.clone(),
525 monitor: monitor.clone(),
529 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
530 last_block_hash: Mutex::new(Default::default()),
533 channel_state: Mutex::new(ChannelHolder{
534 by_id: HashMap::new(),
535 short_to_id: HashMap::new(),
536 next_forward: Instant::now(),
537 forward_htlcs: HashMap::new(),
538 claimable_htlcs: HashMap::new(),
539 pending_msg_events: Vec::new(),
541 our_network_key: keys_manager.get_node_secret(),
543 pending_events: Mutex::new(Vec::new()),
544 total_consistency_lock: RwLock::new(()),
550 let weak_res = Arc::downgrade(&res);
551 res.chain_monitor.register_listener(weak_res);
555 /// Creates a new outbound channel to the given remote node and with the given value.
557 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
558 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
559 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
560 /// may wish to avoid using 0 for user_id here.
562 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
563 /// PeerManager::process_events afterwards.
565 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
566 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
567 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
568 if channel_value_satoshis < 1000 {
569 return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
572 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)?;
573 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
575 let _ = self.total_consistency_lock.read().unwrap();
576 let mut channel_state = self.channel_state.lock().unwrap();
577 match channel_state.by_id.entry(channel.channel_id()) {
578 hash_map::Entry::Occupied(_) => {
579 if cfg!(feature = "fuzztarget") {
580 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
582 panic!("RNG is bad???");
585 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
587 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
588 node_id: their_network_key,
594 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
595 /// more information.
596 pub fn list_channels(&self) -> Vec<ChannelDetails> {
597 let channel_state = self.channel_state.lock().unwrap();
598 let mut res = Vec::with_capacity(channel_state.by_id.len());
599 for (channel_id, channel) in channel_state.by_id.iter() {
600 res.push(ChannelDetails {
601 channel_id: (*channel_id).clone(),
602 short_channel_id: channel.get_short_channel_id(),
603 remote_network_id: channel.get_their_node_id(),
604 channel_value_satoshis: channel.get_value_satoshis(),
605 user_id: channel.get_user_id(),
611 /// Gets the list of usable channels, in random order. Useful as an argument to
612 /// Router::get_route to ensure non-announced channels are used.
613 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
614 let channel_state = self.channel_state.lock().unwrap();
615 let mut res = Vec::with_capacity(channel_state.by_id.len());
616 for (channel_id, channel) in channel_state.by_id.iter() {
617 // Note we use is_live here instead of usable which leads to somewhat confused
618 // internal/external nomenclature, but that's ok cause that's probably what the user
619 // really wanted anyway.
620 if channel.is_live() {
621 res.push(ChannelDetails {
622 channel_id: (*channel_id).clone(),
623 short_channel_id: channel.get_short_channel_id(),
624 remote_network_id: channel.get_their_node_id(),
625 channel_value_satoshis: channel.get_value_satoshis(),
626 user_id: channel.get_user_id(),
633 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
634 /// will be accepted on the given channel, and after additional timeout/the closing of all
635 /// pending HTLCs, the channel will be closed on chain.
637 /// May generate a SendShutdown message event on success, which should be relayed.
638 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
639 let _ = self.total_consistency_lock.read().unwrap();
641 let (mut failed_htlcs, chan_option) = {
642 let mut channel_state_lock = self.channel_state.lock().unwrap();
643 let channel_state = channel_state_lock.borrow_parts();
644 match channel_state.by_id.entry(channel_id.clone()) {
645 hash_map::Entry::Occupied(mut chan_entry) => {
646 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
647 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
648 node_id: chan_entry.get().get_their_node_id(),
651 if chan_entry.get().is_shutdown() {
652 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
653 channel_state.short_to_id.remove(&short_id);
655 (failed_htlcs, Some(chan_entry.remove_entry().1))
656 } else { (failed_htlcs, None) }
658 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
661 for htlc_source in failed_htlcs.drain(..) {
662 // unknown_next_peer...I dunno who that is anymore....
663 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
665 let chan_update = if let Some(chan) = chan_option {
666 if let Ok(update) = self.get_channel_update(&chan) {
671 if let Some(update) = chan_update {
672 let mut channel_state = self.channel_state.lock().unwrap();
673 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
682 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
683 let (local_txn, mut failed_htlcs) = shutdown_res;
684 for htlc_source in failed_htlcs.drain(..) {
685 // unknown_next_peer...I dunno who that is anymore....
686 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
688 for tx in local_txn {
689 self.tx_broadcaster.broadcast_transaction(&tx);
693 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
694 /// the chain and rejecting new HTLCs on the given channel.
695 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
696 let _ = self.total_consistency_lock.read().unwrap();
699 let mut channel_state_lock = self.channel_state.lock().unwrap();
700 let channel_state = channel_state_lock.borrow_parts();
701 if let Some(chan) = channel_state.by_id.remove(channel_id) {
702 if let Some(short_id) = chan.get_short_channel_id() {
703 channel_state.short_to_id.remove(&short_id);
710 self.finish_force_close_channel(chan.force_shutdown());
711 if let Ok(update) = self.get_channel_update(&chan) {
712 let mut channel_state = self.channel_state.lock().unwrap();
713 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
719 /// Force close all channels, immediately broadcasting the latest local commitment transaction
720 /// for each to the chain and rejecting new HTLCs on each.
721 pub fn force_close_all_channels(&self) {
722 for chan in self.list_channels() {
723 self.force_close_channel(&chan.channel_id);
728 fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
729 assert_eq!(shared_secret.len(), 32);
731 let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
732 hmac.input(&shared_secret[..]);
733 let mut res = [0; 32];
734 hmac.raw_result(&mut res);
738 let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
739 hmac.input(&shared_secret[..]);
740 let mut res = [0; 32];
741 hmac.raw_result(&mut res);
747 fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
748 assert_eq!(shared_secret.len(), 32);
749 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
750 hmac.input(&shared_secret[..]);
751 let mut res = [0; 32];
752 hmac.raw_result(&mut res);
757 fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
758 assert_eq!(shared_secret.len(), 32);
759 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
760 hmac.input(&shared_secret[..]);
761 let mut res = [0; 32];
762 hmac.raw_result(&mut res);
766 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
768 fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), secp256k1::Error> {
769 let mut blinded_priv = session_priv.clone();
770 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
772 for hop in route.hops.iter() {
773 let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
775 let mut sha = Sha256::new();
776 sha.input(&blinded_pub.serialize()[..]);
777 sha.input(&shared_secret[..]);
778 let mut blinding_factor = [0u8; 32];
779 sha.result(&mut blinding_factor);
781 let ephemeral_pubkey = blinded_pub;
783 blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
784 blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
786 callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
792 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
793 fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
794 let mut res = Vec::with_capacity(route.hops.len());
796 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
797 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
803 blinding_factor: _blinding_factor,
813 /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
814 fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
815 let mut cur_value_msat = 0u64;
816 let mut cur_cltv = starting_htlc_offset;
817 let mut last_short_channel_id = 0;
818 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
819 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
820 unsafe { res.set_len(route.hops.len()); }
822 for (idx, hop) in route.hops.iter().enumerate().rev() {
823 // First hop gets special values so that it can check, on receipt, that everything is
824 // exactly as it should be (and the next hop isn't trying to probe to find out if we're
825 // the intended recipient).
826 let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
827 let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
828 res[idx] = msgs::OnionHopData {
830 data: msgs::OnionRealm0HopData {
831 short_channel_id: last_short_channel_id,
832 amt_to_forward: value_msat,
833 outgoing_cltv_value: cltv,
837 cur_value_msat += hop.fee_msat;
838 if cur_value_msat >= 21000000 * 100000000 * 1000 {
839 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
841 cur_cltv += hop.cltv_expiry_delta as u32;
842 if cur_cltv >= 500000000 {
843 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
845 last_short_channel_id = hop.short_channel_id;
847 Ok((res, cur_value_msat, cur_cltv))
851 fn shift_arr_right(arr: &mut [u8; 20*65]) {
853 ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
861 fn xor_bufs(dst: &mut[u8], src: &[u8]) {
862 assert_eq!(dst.len(), src.len());
864 for i in 0..dst.len() {
869 const ZERO:[u8; 21*65] = [0; 21*65];
870 fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
871 let mut buf = Vec::with_capacity(21*65);
872 buf.resize(21*65, 0);
875 let iters = payloads.len() - 1;
876 let end_len = iters * 65;
877 let mut res = Vec::with_capacity(end_len);
878 res.resize(end_len, 0);
880 for (i, keys) in onion_keys.iter().enumerate() {
881 if i == payloads.len() - 1 { continue; }
882 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
883 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
884 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
889 let mut packet_data = [0; 20*65];
890 let mut hmac_res = [0; 32];
892 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
893 ChannelManager::shift_arr_right(&mut packet_data);
894 payload.hmac = hmac_res;
895 packet_data[0..65].copy_from_slice(&payload.encode()[..]);
897 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
898 chacha.process(&packet_data, &mut buf[0..20*65]);
899 packet_data[..].copy_from_slice(&buf[0..20*65]);
902 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
905 let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
906 hmac.input(&packet_data);
907 hmac.input(&associated_data.0[..]);
908 hmac.raw_result(&mut hmac_res);
913 public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
914 hop_data: packet_data,
919 /// Encrypts a failure packet. raw_packet can either be a
920 /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
921 fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
922 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
924 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
925 packet_crypted.resize(raw_packet.len(), 0);
926 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
927 chacha.process(&raw_packet, &mut packet_crypted[..]);
928 msgs::OnionErrorPacket {
929 data: packet_crypted,
933 fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
934 assert_eq!(shared_secret.len(), 32);
935 assert!(failure_data.len() <= 256 - 2);
937 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
940 let mut res = Vec::with_capacity(2 + failure_data.len());
941 res.push(((failure_type >> 8) & 0xff) as u8);
942 res.push(((failure_type >> 0) & 0xff) as u8);
943 res.extend_from_slice(&failure_data[..]);
947 let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
948 res.resize(256 - 2 - failure_data.len(), 0);
951 let mut packet = msgs::DecodedOnionErrorPacket {
953 failuremsg: failuremsg,
957 let mut hmac = Hmac::new(Sha256::new(), &um);
958 hmac.input(&packet.encode()[32..]);
959 hmac.raw_result(&mut packet.hmac);
965 fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
966 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
967 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
970 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
971 macro_rules! get_onion_hash {
974 let mut sha = Sha256::new();
975 sha.input(&msg.onion_routing_packet.hop_data);
976 let mut onion_hash = [0; 32];
977 sha.result(&mut onion_hash);
983 if let Err(_) = msg.onion_routing_packet.public_key {
984 log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
985 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
986 channel_id: msg.channel_id,
987 htlc_id: msg.htlc_id,
988 sha256_of_onion: get_onion_hash!(),
989 failure_code: 0x8000 | 0x4000 | 6,
990 })), self.channel_state.lock().unwrap());
993 let shared_secret = {
994 let mut arr = [0; 32];
995 arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
998 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1000 let mut channel_state = None;
1001 macro_rules! return_err {
1002 ($msg: expr, $err_code: expr, $data: expr) => {
1004 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1005 if channel_state.is_none() {
1006 channel_state = Some(self.channel_state.lock().unwrap());
1008 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1009 channel_id: msg.channel_id,
1010 htlc_id: msg.htlc_id,
1011 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1012 })), channel_state.unwrap());
1017 if msg.onion_routing_packet.version != 0 {
1018 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1019 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1020 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1021 //receiving node would have to brute force to figure out which version was put in the
1022 //packet by the node that send us the message, in the case of hashing the hop_data, the
1023 //node knows the HMAC matched, so they already know what is there...
1024 return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1027 let mut hmac = Hmac::new(Sha256::new(), &mu);
1028 hmac.input(&msg.onion_routing_packet.hop_data);
1029 hmac.input(&msg.payment_hash.0[..]);
1030 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1031 return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1034 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1035 let next_hop_data = {
1036 let mut decoded = [0; 65];
1037 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1038 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1040 let error_code = match err {
1041 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1042 _ => 0x2000 | 2, // Should never happen
1044 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1050 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1052 // final_expiry_too_soon
1053 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1054 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1056 // final_incorrect_htlc_amount
1057 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1058 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1060 // final_incorrect_cltv_expiry
1061 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1062 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1065 // Note that we could obviously respond immediately with an update_fulfill_htlc
1066 // message, however that would leak that we are the recipient of this payment, so
1067 // instead we stay symmetric with the forwarding case, only responding (after a
1068 // delay) once they've send us a commitment_signed!
1070 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1072 payment_hash: msg.payment_hash.clone(),
1073 short_channel_id: 0,
1074 incoming_shared_secret: shared_secret,
1075 amt_to_forward: next_hop_data.data.amt_to_forward,
1076 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1079 let mut new_packet_data = [0; 20*65];
1080 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1081 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1083 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1085 let blinding_factor = {
1086 let mut sha = Sha256::new();
1087 sha.input(&new_pubkey.serialize()[..]);
1088 sha.input(&shared_secret);
1089 let mut res = [0u8; 32];
1090 sha.result(&mut res);
1091 match SecretKey::from_slice(&self.secp_ctx, &res) {
1093 return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1099 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1100 return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1103 let outgoing_packet = msgs::OnionPacket {
1105 public_key: Ok(new_pubkey),
1106 hop_data: new_packet_data,
1107 hmac: next_hop_data.hmac.clone(),
1110 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1111 onion_packet: Some(outgoing_packet),
1112 payment_hash: msg.payment_hash.clone(),
1113 short_channel_id: next_hop_data.data.short_channel_id,
1114 incoming_shared_secret: shared_secret,
1115 amt_to_forward: next_hop_data.data.amt_to_forward,
1116 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1120 channel_state = Some(self.channel_state.lock().unwrap());
1121 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1122 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1123 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1124 let forwarding_id = match id_option {
1125 None => { // unknown_next_peer
1126 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1128 Some(id) => id.clone(),
1130 if let Some((err, code, chan_update)) = loop {
1131 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1133 // Note that we could technically not return an error yet here and just hope
1134 // that the connection is reestablished or monitor updated by the time we get
1135 // around to doing the actual forward, but better to fail early if we can and
1136 // hopefully an attacker trying to path-trace payments cannot make this occur
1137 // on a small/per-node/per-channel scale.
1138 if !chan.is_live() { // channel_disabled
1139 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1141 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1142 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1144 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) });
1145 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1146 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())));
1148 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1149 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())));
1151 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1152 // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1153 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1154 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1156 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1157 break Some(("CLTV expiry is too far in the future", 21, None));
1162 let mut res = Vec::with_capacity(8 + 128);
1163 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1164 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1166 else if code == 0x1000 | 13 {
1167 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1169 if let Some(chan_update) = chan_update {
1170 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1172 return_err!(err, code, &res[..]);
1177 (pending_forward_info, channel_state.unwrap())
1180 /// only fails if the channel does not yet have an assigned short_id
1181 /// May be called with channel_state already locked!
1182 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1183 let short_channel_id = match chan.get_short_channel_id() {
1184 None => return Err(HandleError{err: "Channel not yet established", action: None}),
1188 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1190 let unsigned = msgs::UnsignedChannelUpdate {
1191 chain_hash: self.genesis_hash,
1192 short_channel_id: short_channel_id,
1193 timestamp: chan.get_channel_update_count(),
1194 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1195 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1196 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1197 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1198 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1199 excess_data: Vec::new(),
1202 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1203 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1205 Ok(msgs::ChannelUpdate {
1211 /// Sends a payment along a given route.
1213 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1214 /// fields for more info.
1216 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1217 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1218 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1219 /// specified in the last hop in the route! Thus, you should probably do your own
1220 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1221 /// payment") and prevent double-sends yourself.
1223 /// May generate a SendHTLCs message event on success, which should be relayed.
1225 /// Raises APIError::RoutError when invalid route or forward parameter
1226 /// (cltv_delta, fee, node public key) is specified.
1227 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1228 /// (including due to previous monitor update failure or new permanent monitor update failure).
1229 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1230 /// relevant updates.
1232 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1233 /// and you may wish to retry via a different route immediately.
1234 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1235 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1236 /// the payment via a different route unless you intend to pay twice!
1237 pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1238 if route.hops.len() < 1 || route.hops.len() > 20 {
1239 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1241 let our_node_id = self.get_our_node_id();
1242 for (idx, hop) in route.hops.iter().enumerate() {
1243 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1244 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1248 let session_priv = self.keys_manager.get_session_key();
1250 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1252 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1253 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1254 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1255 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1257 let _ = self.total_consistency_lock.read().unwrap();
1259 let err: Result<(), _> = loop {
1260 let mut channel_lock = self.channel_state.lock().unwrap();
1262 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1263 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1264 Some(id) => id.clone(),
1267 let channel_state = channel_lock.borrow_parts();
1268 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1270 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1271 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1273 if !chan.get().is_live() {
1274 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1276 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1277 route: route.clone(),
1278 session_priv: session_priv.clone(),
1279 first_hop_htlc_msat: htlc_msat,
1280 }, onion_packet), channel_state, chan)
1282 Some((update_add, commitment_signed, chan_monitor)) => {
1283 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1284 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1285 // Note that MonitorUpdateFailed here indicates (per function docs)
1286 // that we will resent the commitment update once we unfree monitor
1287 // updating, so we have to take special care that we don't return
1288 // something else in case we will resend later!
1289 return Err(APIError::MonitorUpdateFailed);
1292 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1293 node_id: route.hops.first().unwrap().pubkey,
1294 updates: msgs::CommitmentUpdate {
1295 update_add_htlcs: vec![update_add],
1296 update_fulfill_htlcs: Vec::new(),
1297 update_fail_htlcs: Vec::new(),
1298 update_fail_malformed_htlcs: Vec::new(),
1306 } else { unreachable!(); }
1310 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1311 Ok(_) => unreachable!(),
1313 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1315 log_error!(self, "Got bad keys: {}!", e.err);
1316 let mut channel_state = self.channel_state.lock().unwrap();
1317 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1318 node_id: route.hops.first().unwrap().pubkey,
1322 Err(APIError::ChannelUnavailable { err: e.err })
1327 /// Call this upon creation of a funding transaction for the given channel.
1329 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1330 /// or your counterparty can steal your funds!
1332 /// Panics if a funding transaction has already been provided for this channel.
1334 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1335 /// be trivially prevented by using unique funding transaction keys per-channel).
1336 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1337 let _ = self.total_consistency_lock.read().unwrap();
1339 let (chan, msg, chan_monitor) = {
1341 let mut channel_state = self.channel_state.lock().unwrap();
1342 match channel_state.by_id.remove(temporary_channel_id) {
1344 (chan.get_outbound_funding_created(funding_txo)
1345 .map_err(|e| if let ChannelError::Close(msg) = e {
1346 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1347 } else { unreachable!(); })
1353 match handle_error!(self, res, chan.get_their_node_id()) {
1354 Ok(funding_msg) => {
1355 (chan, funding_msg.0, funding_msg.1)
1358 log_error!(self, "Got bad signatures: {}!", e.err);
1359 let mut channel_state = self.channel_state.lock().unwrap();
1360 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1361 node_id: chan.get_their_node_id(),
1368 // Because we have exclusive ownership of the channel here we can release the channel_state
1369 // lock before add_update_monitor
1370 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1374 let mut channel_state = self.channel_state.lock().unwrap();
1375 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1376 node_id: chan.get_their_node_id(),
1379 match channel_state.by_id.entry(chan.channel_id()) {
1380 hash_map::Entry::Occupied(_) => {
1381 panic!("Generated duplicate funding txid?");
1383 hash_map::Entry::Vacant(e) => {
1389 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1390 if !chan.should_announce() { return None }
1392 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1394 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1396 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1397 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1399 Some(msgs::AnnouncementSignatures {
1400 channel_id: chan.channel_id(),
1401 short_channel_id: chan.get_short_channel_id().unwrap(),
1402 node_signature: our_node_sig,
1403 bitcoin_signature: our_bitcoin_sig,
1407 /// Processes HTLCs which are pending waiting on random forward delay.
1409 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1410 /// Will likely generate further events.
1411 pub fn process_pending_htlc_forwards(&self) {
1412 let _ = self.total_consistency_lock.read().unwrap();
1414 let mut new_events = Vec::new();
1415 let mut failed_forwards = Vec::new();
1417 let mut channel_state_lock = self.channel_state.lock().unwrap();
1418 let channel_state = channel_state_lock.borrow_parts();
1420 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1424 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1425 if short_chan_id != 0 {
1426 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1427 Some(chan_id) => chan_id.clone(),
1429 failed_forwards.reserve(pending_forwards.len());
1430 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1431 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1432 short_channel_id: prev_short_channel_id,
1433 htlc_id: prev_htlc_id,
1434 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1436 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1441 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1443 let mut add_htlc_msgs = Vec::new();
1444 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1445 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1446 short_channel_id: prev_short_channel_id,
1447 htlc_id: prev_htlc_id,
1448 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1450 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()) {
1452 let chan_update = self.get_channel_update(forward_chan).unwrap();
1453 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1458 Some(msg) => { add_htlc_msgs.push(msg); },
1460 // Nothing to do here...we're waiting on a remote
1461 // revoke_and_ack before we can add anymore HTLCs. The Channel
1462 // will automatically handle building the update_add_htlc and
1463 // commitment_signed messages when we can.
1464 // TODO: Do some kind of timer to set the channel as !is_live()
1465 // as we don't really want others relying on us relaying through
1466 // this channel currently :/.
1473 if !add_htlc_msgs.is_empty() {
1474 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1477 if let ChannelError::Ignore(_) = e {
1478 panic!("Stated return value requirements in send_commitment() were not met");
1480 //TODO: Handle...this is bad!
1484 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1487 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1488 node_id: forward_chan.get_their_node_id(),
1489 updates: msgs::CommitmentUpdate {
1490 update_add_htlcs: add_htlc_msgs,
1491 update_fulfill_htlcs: Vec::new(),
1492 update_fail_htlcs: Vec::new(),
1493 update_fail_malformed_htlcs: Vec::new(),
1495 commitment_signed: commitment_msg,
1500 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1501 let prev_hop_data = HTLCPreviousHopData {
1502 short_channel_id: prev_short_channel_id,
1503 htlc_id: prev_htlc_id,
1504 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1506 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1507 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1508 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1510 new_events.push(events::Event::PaymentReceived {
1511 payment_hash: forward_info.payment_hash,
1512 amt: forward_info.amt_to_forward,
1519 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1521 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1522 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() }),
1526 if new_events.is_empty() { return }
1527 let mut events = self.pending_events.lock().unwrap();
1528 events.append(&mut new_events);
1531 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1532 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1533 let _ = self.total_consistency_lock.read().unwrap();
1535 let mut channel_state = Some(self.channel_state.lock().unwrap());
1536 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1537 if let Some(mut sources) = removed_source {
1538 for htlc_with_hash in sources.drain(..) {
1539 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1540 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: if reason == PaymentFailReason::PreimageUnknown {0x4000 | 15} else {0x4000 | 16}, data: Vec::new() });
1546 /// Fails an HTLC backwards to the sender of it to us.
1547 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1548 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1549 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1550 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1551 /// still-available channels.
1552 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1554 HTLCSource::OutboundRoute { .. } => {
1555 mem::drop(channel_state_lock);
1556 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1557 let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1558 if let Some(update) = channel_update {
1559 self.channel_state.lock().unwrap().pending_msg_events.push(
1560 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1565 self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1566 payment_hash: payment_hash.clone(),
1567 rejected_by_dest: !payment_retryable,
1570 //TODO: Pass this back (see GH #243)
1571 self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1572 payment_hash: payment_hash.clone(),
1573 rejected_by_dest: false, // We failed it ourselves, can't blame them
1577 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1578 let err_packet = match onion_error {
1579 HTLCFailReason::Reason { failure_code, data } => {
1580 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1581 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1583 HTLCFailReason::ErrorPacket { err } => {
1584 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1588 let channel_state = channel_state_lock.borrow_parts();
1590 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1591 Some(chan_id) => chan_id.clone(),
1595 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1596 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1597 Ok(Some((msg, commitment_msg, chan_monitor))) => {
1598 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1601 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1602 node_id: chan.get_their_node_id(),
1603 updates: msgs::CommitmentUpdate {
1604 update_add_htlcs: Vec::new(),
1605 update_fulfill_htlcs: Vec::new(),
1606 update_fail_htlcs: vec![msg],
1607 update_fail_malformed_htlcs: Vec::new(),
1609 commitment_signed: commitment_msg,
1615 //TODO: Do something with e?
1623 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1624 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1625 /// should probably kick the net layer to go send messages if this returns true!
1627 /// May panic if called except in response to a PaymentReceived event.
1628 pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1629 let mut sha = Sha256::new();
1630 sha.input(&payment_preimage.0[..]);
1631 let mut payment_hash = PaymentHash([0; 32]);
1632 sha.result(&mut payment_hash.0[..]);
1634 let _ = self.total_consistency_lock.read().unwrap();
1636 let mut channel_state = Some(self.channel_state.lock().unwrap());
1637 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1638 if let Some(mut sources) = removed_source {
1639 for htlc_with_hash in sources.drain(..) {
1640 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1641 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1646 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1648 HTLCSource::OutboundRoute { .. } => {
1649 mem::drop(channel_state_lock);
1650 let mut pending_events = self.pending_events.lock().unwrap();
1651 pending_events.push(events::Event::PaymentSent {
1655 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1656 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1657 let channel_state = channel_state_lock.borrow_parts();
1659 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1660 Some(chan_id) => chan_id.clone(),
1662 // TODO: There is probably a channel manager somewhere that needs to
1663 // learn the preimage as the channel already hit the chain and that's
1669 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1670 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1671 Ok((msgs, monitor_option)) => {
1672 if let Some(chan_monitor) = monitor_option {
1673 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1674 unimplemented!();// but def dont push the event...
1677 if let Some((msg, commitment_signed)) = msgs {
1678 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1679 node_id: chan.get_their_node_id(),
1680 updates: msgs::CommitmentUpdate {
1681 update_add_htlcs: Vec::new(),
1682 update_fulfill_htlcs: vec![msg],
1683 update_fail_htlcs: Vec::new(),
1684 update_fail_malformed_htlcs: Vec::new(),
1692 // TODO: There is probably a channel manager somewhere that needs to
1693 // learn the preimage as the channel may be about to hit the chain.
1694 //TODO: Do something with e?
1702 /// Gets the node_id held by this ChannelManager
1703 pub fn get_our_node_id(&self) -> PublicKey {
1704 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1707 /// Used to restore channels to normal operation after a
1708 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1710 pub fn test_restore_channel_monitor(&self) {
1711 let mut close_results = Vec::new();
1712 let mut htlc_forwards = Vec::new();
1713 let mut htlc_failures = Vec::new();
1714 let _ = self.total_consistency_lock.read().unwrap();
1717 let mut channel_lock = self.channel_state.lock().unwrap();
1718 let channel_state = channel_lock.borrow_parts();
1719 let short_to_id = channel_state.short_to_id;
1720 let pending_msg_events = channel_state.pending_msg_events;
1721 channel_state.by_id.retain(|_, channel| {
1722 if channel.is_awaiting_monitor_update() {
1723 let chan_monitor = channel.channel_monitor();
1724 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1726 ChannelMonitorUpdateErr::PermanentFailure => {
1727 // TODO: There may be some pending HTLCs that we intended to fail
1728 // backwards when a monitor update failed. We should make sure
1729 // knowledge of those gets moved into the appropriate in-memory
1730 // ChannelMonitor and they get failed backwards once we get
1731 // on-chain confirmations.
1732 // Note I think #198 addresses this, so once its merged a test
1733 // should be written.
1734 if let Some(short_id) = channel.get_short_channel_id() {
1735 short_to_id.remove(&short_id);
1737 close_results.push(channel.force_shutdown());
1738 if let Ok(update) = self.get_channel_update(&channel) {
1739 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1745 ChannelMonitorUpdateErr::TemporaryFailure => true,
1748 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1749 if !pending_forwards.is_empty() {
1750 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1752 htlc_failures.append(&mut pending_failures);
1754 macro_rules! handle_cs { () => {
1755 if let Some(update) = commitment_update {
1756 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1757 node_id: channel.get_their_node_id(),
1762 macro_rules! handle_raa { () => {
1763 if let Some(revoke_and_ack) = raa {
1764 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1765 node_id: channel.get_their_node_id(),
1766 msg: revoke_and_ack,
1771 RAACommitmentOrder::CommitmentFirst => {
1775 RAACommitmentOrder::RevokeAndACKFirst => {
1786 for failure in htlc_failures.drain(..) {
1787 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1789 self.forward_htlcs(&mut htlc_forwards[..]);
1791 for res in close_results.drain(..) {
1792 self.finish_force_close_channel(res);
1796 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1797 if msg.chain_hash != self.genesis_hash {
1798 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1801 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)
1802 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1803 let mut channel_state_lock = self.channel_state.lock().unwrap();
1804 let channel_state = channel_state_lock.borrow_parts();
1805 match channel_state.by_id.entry(channel.channel_id()) {
1806 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1807 hash_map::Entry::Vacant(entry) => {
1808 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1809 node_id: their_node_id.clone(),
1810 msg: channel.get_accept_channel(),
1812 entry.insert(channel);
1818 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1819 let (value, output_script, user_id) = {
1820 let mut channel_lock = self.channel_state.lock().unwrap();
1821 let channel_state = channel_lock.borrow_parts();
1822 match channel_state.by_id.entry(msg.temporary_channel_id) {
1823 hash_map::Entry::Occupied(mut chan) => {
1824 if chan.get().get_their_node_id() != *their_node_id {
1825 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1826 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1828 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1829 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1831 //TODO: same as above
1832 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1835 let mut pending_events = self.pending_events.lock().unwrap();
1836 pending_events.push(events::Event::FundingGenerationReady {
1837 temporary_channel_id: msg.temporary_channel_id,
1838 channel_value_satoshis: value,
1839 output_script: output_script,
1840 user_channel_id: user_id,
1845 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1846 let ((funding_msg, monitor_update), chan) = {
1847 let mut channel_lock = self.channel_state.lock().unwrap();
1848 let channel_state = channel_lock.borrow_parts();
1849 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1850 hash_map::Entry::Occupied(mut chan) => {
1851 if chan.get().get_their_node_id() != *their_node_id {
1852 //TODO: here and below MsgHandleErrInternal, #153 case
1853 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1855 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1857 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1860 // Because we have exclusive ownership of the channel here we can release the channel_state
1861 // lock before add_update_monitor
1862 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1865 let mut channel_state_lock = self.channel_state.lock().unwrap();
1866 let channel_state = channel_state_lock.borrow_parts();
1867 match channel_state.by_id.entry(funding_msg.channel_id) {
1868 hash_map::Entry::Occupied(_) => {
1869 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1871 hash_map::Entry::Vacant(e) => {
1872 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1873 node_id: their_node_id.clone(),
1882 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1883 let (funding_txo, user_id) = {
1884 let mut channel_lock = self.channel_state.lock().unwrap();
1885 let channel_state = channel_lock.borrow_parts();
1886 match channel_state.by_id.entry(msg.channel_id) {
1887 hash_map::Entry::Occupied(mut chan) => {
1888 if chan.get().get_their_node_id() != *their_node_id {
1889 //TODO: here and below MsgHandleErrInternal, #153 case
1890 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1892 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1893 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1896 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1898 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1901 let mut pending_events = self.pending_events.lock().unwrap();
1902 pending_events.push(events::Event::FundingBroadcastSafe {
1903 funding_txo: funding_txo,
1904 user_channel_id: user_id,
1909 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1910 let mut channel_state_lock = self.channel_state.lock().unwrap();
1911 let channel_state = channel_state_lock.borrow_parts();
1912 match channel_state.by_id.entry(msg.channel_id) {
1913 hash_map::Entry::Occupied(mut chan) => {
1914 if chan.get().get_their_node_id() != *their_node_id {
1915 //TODO: here and below MsgHandleErrInternal, #153 case
1916 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1918 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1919 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1920 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1921 node_id: their_node_id.clone(),
1922 msg: announcement_sigs,
1927 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1931 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1932 let (mut dropped_htlcs, chan_option) = {
1933 let mut channel_state_lock = self.channel_state.lock().unwrap();
1934 let channel_state = channel_state_lock.borrow_parts();
1936 match channel_state.by_id.entry(msg.channel_id.clone()) {
1937 hash_map::Entry::Occupied(mut chan_entry) => {
1938 if chan_entry.get().get_their_node_id() != *their_node_id {
1939 //TODO: here and below MsgHandleErrInternal, #153 case
1940 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1942 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1943 if let Some(msg) = shutdown {
1944 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1945 node_id: their_node_id.clone(),
1949 if let Some(msg) = closing_signed {
1950 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1951 node_id: their_node_id.clone(),
1955 if chan_entry.get().is_shutdown() {
1956 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1957 channel_state.short_to_id.remove(&short_id);
1959 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1960 } else { (dropped_htlcs, None) }
1962 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1965 for htlc_source in dropped_htlcs.drain(..) {
1966 // unknown_next_peer...I dunno who that is anymore....
1967 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1969 if let Some(chan) = chan_option {
1970 if let Ok(update) = self.get_channel_update(&chan) {
1971 let mut channel_state = self.channel_state.lock().unwrap();
1972 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1980 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1981 let (tx, chan_option) = {
1982 let mut channel_state_lock = self.channel_state.lock().unwrap();
1983 let channel_state = channel_state_lock.borrow_parts();
1984 match channel_state.by_id.entry(msg.channel_id.clone()) {
1985 hash_map::Entry::Occupied(mut chan_entry) => {
1986 if chan_entry.get().get_their_node_id() != *their_node_id {
1987 //TODO: here and below MsgHandleErrInternal, #153 case
1988 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1990 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1991 if let Some(msg) = closing_signed {
1992 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1993 node_id: their_node_id.clone(),
1998 // We're done with this channel, we've got a signed closing transaction and
1999 // will send the closing_signed back to the remote peer upon return. This
2000 // also implies there are no pending HTLCs left on the channel, so we can
2001 // fully delete it from tracking (the channel monitor is still around to
2002 // watch for old state broadcasts)!
2003 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2004 channel_state.short_to_id.remove(&short_id);
2006 (tx, Some(chan_entry.remove_entry().1))
2007 } else { (tx, None) }
2009 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2012 if let Some(broadcast_tx) = tx {
2013 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2015 if let Some(chan) = chan_option {
2016 if let Ok(update) = self.get_channel_update(&chan) {
2017 let mut channel_state = self.channel_state.lock().unwrap();
2018 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2026 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2027 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2028 //determine the state of the payment based on our response/if we forward anything/the time
2029 //we take to respond. We should take care to avoid allowing such an attack.
2031 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2032 //us repeatedly garbled in different ways, and compare our error messages, which are
2033 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2034 //but we should prevent it anyway.
2036 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2037 let channel_state = channel_state_lock.borrow_parts();
2039 match channel_state.by_id.entry(msg.channel_id) {
2040 hash_map::Entry::Occupied(mut chan) => {
2041 if chan.get().get_their_node_id() != *their_node_id {
2042 //TODO: here MsgHandleErrInternal, #153 case
2043 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2045 if !chan.get().is_usable() {
2046 // If the update_add is completely bogus, the call will Err and we will close,
2047 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2048 // want to reject the new HTLC and fail it backwards instead of forwarding.
2049 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2050 let chan_update = self.get_channel_update(chan.get());
2051 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2052 channel_id: msg.channel_id,
2053 htlc_id: msg.htlc_id,
2054 reason: if let Ok(update) = chan_update {
2055 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2057 // This can only happen if the channel isn't in the fully-funded
2058 // state yet, implying our counterparty is trying to route payments
2059 // over the channel back to themselves (cause no one else should
2060 // know the short_id is a lightning channel yet). We should have no
2061 // problem just calling this unknown_next_peer
2062 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2067 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2069 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2074 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2075 let mut channel_lock = self.channel_state.lock().unwrap();
2077 let channel_state = channel_lock.borrow_parts();
2078 match channel_state.by_id.entry(msg.channel_id) {
2079 hash_map::Entry::Occupied(mut chan) => {
2080 if chan.get().get_their_node_id() != *their_node_id {
2081 //TODO: here and below MsgHandleErrInternal, #153 case
2082 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2084 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2086 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2089 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2093 // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2094 // indicating that the payment itself failed
2095 fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2096 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2097 macro_rules! onion_failure_log {
2098 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2099 log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2101 ( $error_code_textual: expr, $error_code: expr ) => {
2102 log_trace!(self, "{}({})", $error_code_textual, $error_code);
2106 const BADONION: u16 = 0x8000;
2107 const PERM: u16 = 0x4000;
2108 const UPDATE: u16 = 0x1000;
2111 let mut htlc_msat = *first_hop_htlc_msat;
2113 // Handle packed channel/node updates for passing back for the route handler
2114 Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2115 if res.is_some() { return; }
2117 let incoming_htlc_msat = htlc_msat;
2118 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2119 htlc_msat = amt_to_forward;
2121 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2123 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2124 decryption_tmp.resize(packet_decrypted.len(), 0);
2125 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2126 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2127 packet_decrypted = decryption_tmp;
2129 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2131 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2132 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2133 let mut hmac = Hmac::new(Sha256::new(), &um);
2134 hmac.input(&err_packet.encode()[32..]);
2135 let mut calc_tag = [0u8; 32];
2136 hmac.raw_result(&mut calc_tag);
2138 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2139 if err_packet.failuremsg.len() < 2 {
2140 // Useless packet that we can't use but it passed HMAC, so it
2141 // definitely came from the peer in question
2142 res = Some((None, !is_from_final_node));
2144 let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2146 match error_code & 0xff {
2148 // either from an intermediate or final node
2149 // invalid_realm(PERM|1),
2150 // temporary_node_failure(NODE|2)
2151 // permanent_node_failure(PERM|NODE|2)
2152 // required_node_feature_mssing(PERM|NODE|3)
2153 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2154 node_id: route_hop.pubkey,
2155 is_permanent: error_code & PERM == PERM,
2156 }), !(error_code & PERM == PERM && is_from_final_node)));
2157 // node returning invalid_realm is removed from network_map,
2158 // although NODE flag is not set, TODO: or remove channel only?
2159 // retry payment when removed node is not a final node
2165 if is_from_final_node {
2166 let payment_retryable = match error_code {
2167 c if c == PERM|15 => false, // unknown_payment_hash
2168 c if c == PERM|16 => false, // incorrect_payment_amount
2169 17 => true, // final_expiry_too_soon
2170 18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2171 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2174 19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2175 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2179 // A final node has sent us either an invalid code or an error_code that
2180 // MUST be sent from the processing node, or the formmat of failuremsg
2181 // does not coform to the spec.
2182 // Remove it from the network map and don't may retry payment
2183 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2184 node_id: route_hop.pubkey,
2190 res = Some((None, payment_retryable));
2194 // now, error_code should be only from the intermediate nodes
2196 _c if error_code & PERM == PERM => {
2197 res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2198 short_channel_id: route_hop.short_channel_id,
2202 _c if error_code & UPDATE == UPDATE => {
2203 let offset = match error_code {
2204 c if c == UPDATE|7 => 0, // temporary_channel_failure
2205 c if c == UPDATE|11 => 8, // amount_below_minimum
2206 c if c == UPDATE|12 => 8, // fee_insufficient
2207 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2208 c if c == UPDATE|14 => 0, // expiry_too_soon
2209 c if c == UPDATE|20 => 2, // channel_disabled
2211 // node sending unknown code
2212 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2213 node_id: route_hop.pubkey,
2220 if err_packet.failuremsg.len() >= offset + 2 {
2221 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2222 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2223 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2224 // if channel_update should NOT have caused the failure:
2225 // MAY treat the channel_update as invalid.
2226 let is_chan_update_invalid = match error_code {
2227 c if c == UPDATE|7 => { // temporary_channel_failure
2230 c if c == UPDATE|11 => { // amount_below_minimum
2231 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2232 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2233 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2235 c if c == UPDATE|12 => { // fee_insufficient
2236 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2237 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) });
2238 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2239 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2241 c if c == UPDATE|13 => { // incorrect_cltv_expiry
2242 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2243 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2244 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2246 c if c == UPDATE|20 => { // channel_disabled
2247 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2248 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2249 chan_update.contents.flags & 0x01 == 0x01
2251 c if c == UPDATE|21 => true, // expiry_too_far
2252 _ => { unreachable!(); },
2255 let msg = if is_chan_update_invalid { None } else {
2256 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2260 res = Some((msg, true));
2266 _c if error_code & BADONION == BADONION => {
2269 14 => { // expiry_too_soon
2270 res = Some((None, true));
2274 // node sending unknown code
2275 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2276 node_id: route_hop.pubkey,
2285 }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2286 res.unwrap_or((None, true))
2287 } else { ((None, true)) }
2290 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2291 let mut channel_lock = self.channel_state.lock().unwrap();
2292 let channel_state = channel_lock.borrow_parts();
2293 match channel_state.by_id.entry(msg.channel_id) {
2294 hash_map::Entry::Occupied(mut chan) => {
2295 if chan.get().get_their_node_id() != *their_node_id {
2296 //TODO: here and below MsgHandleErrInternal, #153 case
2297 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2299 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2301 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2306 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2307 let mut channel_lock = self.channel_state.lock().unwrap();
2308 let channel_state = channel_lock.borrow_parts();
2309 match channel_state.by_id.entry(msg.channel_id) {
2310 hash_map::Entry::Occupied(mut chan) => {
2311 if chan.get().get_their_node_id() != *their_node_id {
2312 //TODO: here and below MsgHandleErrInternal, #153 case
2313 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2315 if (msg.failure_code & 0x8000) == 0 {
2316 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2318 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);
2321 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2325 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2326 let mut channel_state_lock = self.channel_state.lock().unwrap();
2327 let channel_state = channel_state_lock.borrow_parts();
2328 match channel_state.by_id.entry(msg.channel_id) {
2329 hash_map::Entry::Occupied(mut chan) => {
2330 if chan.get().get_their_node_id() != *their_node_id {
2331 //TODO: here and below MsgHandleErrInternal, #153 case
2332 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2334 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2335 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2336 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2337 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2338 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2340 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2341 node_id: their_node_id.clone(),
2342 msg: revoke_and_ack,
2344 if let Some(msg) = commitment_signed {
2345 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2346 node_id: their_node_id.clone(),
2347 updates: msgs::CommitmentUpdate {
2348 update_add_htlcs: Vec::new(),
2349 update_fulfill_htlcs: Vec::new(),
2350 update_fail_htlcs: Vec::new(),
2351 update_fail_malformed_htlcs: Vec::new(),
2353 commitment_signed: msg,
2357 if let Some(msg) = closing_signed {
2358 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2359 node_id: their_node_id.clone(),
2365 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2370 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2371 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2372 let mut forward_event = None;
2373 if !pending_forwards.is_empty() {
2374 let mut channel_state = self.channel_state.lock().unwrap();
2375 if channel_state.forward_htlcs.is_empty() {
2376 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));
2377 channel_state.next_forward = forward_event.unwrap();
2379 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2380 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2381 hash_map::Entry::Occupied(mut entry) => {
2382 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2384 hash_map::Entry::Vacant(entry) => {
2385 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2390 match forward_event {
2392 let mut pending_events = self.pending_events.lock().unwrap();
2393 pending_events.push(events::Event::PendingHTLCsForwardable {
2394 time_forwardable: time
2402 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2403 let (pending_forwards, mut pending_failures, short_channel_id) = {
2404 let mut channel_state_lock = self.channel_state.lock().unwrap();
2405 let channel_state = channel_state_lock.borrow_parts();
2406 match channel_state.by_id.entry(msg.channel_id) {
2407 hash_map::Entry::Occupied(mut chan) => {
2408 if chan.get().get_their_node_id() != *their_node_id {
2409 //TODO: here and below MsgHandleErrInternal, #153 case
2410 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2412 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2413 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2414 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2415 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2417 if let Some(updates) = commitment_update {
2418 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2419 node_id: their_node_id.clone(),
2423 if let Some(msg) = closing_signed {
2424 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2425 node_id: their_node_id.clone(),
2429 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2431 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2434 for failure in pending_failures.drain(..) {
2435 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2437 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2442 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2443 let mut channel_lock = self.channel_state.lock().unwrap();
2444 let channel_state = channel_lock.borrow_parts();
2445 match channel_state.by_id.entry(msg.channel_id) {
2446 hash_map::Entry::Occupied(mut chan) => {
2447 if chan.get().get_their_node_id() != *their_node_id {
2448 //TODO: here and below MsgHandleErrInternal, #153 case
2449 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2451 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2453 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2458 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2459 let mut channel_state_lock = self.channel_state.lock().unwrap();
2460 let channel_state = channel_state_lock.borrow_parts();
2462 match channel_state.by_id.entry(msg.channel_id) {
2463 hash_map::Entry::Occupied(mut chan) => {
2464 if chan.get().get_their_node_id() != *their_node_id {
2465 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2467 if !chan.get().is_usable() {
2468 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2471 let our_node_id = self.get_our_node_id();
2472 let (announcement, our_bitcoin_sig) =
2473 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2475 let were_node_one = announcement.node_id_1 == our_node_id;
2476 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2477 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2478 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2479 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2482 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2484 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2485 msg: msgs::ChannelAnnouncement {
2486 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2487 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2488 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2489 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2490 contents: announcement,
2492 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2495 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2500 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2501 let mut channel_state_lock = self.channel_state.lock().unwrap();
2502 let channel_state = channel_state_lock.borrow_parts();
2504 match channel_state.by_id.entry(msg.channel_id) {
2505 hash_map::Entry::Occupied(mut chan) => {
2506 if chan.get().get_their_node_id() != *their_node_id {
2507 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2509 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2510 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2511 if let Some(monitor) = channel_monitor {
2512 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2513 // channel_reestablish doesn't guarantee the order it returns is sensical
2514 // for the messages it returns, but if we're setting what messages to
2515 // re-transmit on monitor update success, we need to make sure it is sane.
2516 if revoke_and_ack.is_none() {
2517 order = RAACommitmentOrder::CommitmentFirst;
2519 if commitment_update.is_none() {
2520 order = RAACommitmentOrder::RevokeAndACKFirst;
2522 return_monitor_err!(self, e, channel_state, chan, order);
2523 //TODO: Resend the funding_locked if needed once we get the monitor running again
2526 if let Some(msg) = funding_locked {
2527 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2528 node_id: their_node_id.clone(),
2532 macro_rules! send_raa { () => {
2533 if let Some(msg) = revoke_and_ack {
2534 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2535 node_id: their_node_id.clone(),
2540 macro_rules! send_cu { () => {
2541 if let Some(updates) = commitment_update {
2542 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2543 node_id: their_node_id.clone(),
2549 RAACommitmentOrder::RevokeAndACKFirst => {
2553 RAACommitmentOrder::CommitmentFirst => {
2558 if let Some(msg) = shutdown {
2559 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2560 node_id: their_node_id.clone(),
2566 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2570 /// Begin Update fee process. Allowed only on an outbound channel.
2571 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2572 /// PeerManager::process_events afterwards.
2573 /// Note: This API is likely to change!
2575 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2576 let _ = self.total_consistency_lock.read().unwrap();
2578 let err: Result<(), _> = loop {
2579 let mut channel_state_lock = self.channel_state.lock().unwrap();
2580 let channel_state = channel_state_lock.borrow_parts();
2582 match channel_state.by_id.entry(channel_id) {
2583 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2584 hash_map::Entry::Occupied(mut chan) => {
2585 if !chan.get().is_outbound() {
2586 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2588 if chan.get().is_awaiting_monitor_update() {
2589 return Err(APIError::MonitorUpdateFailed);
2591 if !chan.get().is_live() {
2592 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2594 their_node_id = chan.get().get_their_node_id();
2595 if let Some((update_fee, commitment_signed, chan_monitor)) =
2596 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2598 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2601 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2602 node_id: chan.get().get_their_node_id(),
2603 updates: msgs::CommitmentUpdate {
2604 update_add_htlcs: Vec::new(),
2605 update_fulfill_htlcs: Vec::new(),
2606 update_fail_htlcs: Vec::new(),
2607 update_fail_malformed_htlcs: Vec::new(),
2608 update_fee: Some(update_fee),
2618 match handle_error!(self, err, their_node_id) {
2619 Ok(_) => unreachable!(),
2621 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2623 log_error!(self, "Got bad keys: {}!", e.err);
2624 let mut channel_state = self.channel_state.lock().unwrap();
2625 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2626 node_id: their_node_id,
2630 Err(APIError::APIMisuseError { err: e.err })
2636 impl events::MessageSendEventsProvider for ChannelManager {
2637 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2638 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2639 // user to serialize a ChannelManager with pending events in it and lose those events on
2640 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2642 //TODO: This behavior should be documented.
2643 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2644 if let Some(preimage) = htlc_update.payment_preimage {
2645 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2647 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2652 let mut ret = Vec::new();
2653 let mut channel_state = self.channel_state.lock().unwrap();
2654 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2659 impl events::EventsProvider for ChannelManager {
2660 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2661 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2662 // user to serialize a ChannelManager with pending events in it and lose those events on
2663 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2665 //TODO: This behavior should be documented.
2666 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2667 if let Some(preimage) = htlc_update.payment_preimage {
2668 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2670 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2675 let mut ret = Vec::new();
2676 let mut pending_events = self.pending_events.lock().unwrap();
2677 mem::swap(&mut ret, &mut *pending_events);
2682 impl ChainListener for ChannelManager {
2683 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2684 let _ = self.total_consistency_lock.read().unwrap();
2685 let mut failed_channels = Vec::new();
2687 let mut channel_lock = self.channel_state.lock().unwrap();
2688 let channel_state = channel_lock.borrow_parts();
2689 let short_to_id = channel_state.short_to_id;
2690 let pending_msg_events = channel_state.pending_msg_events;
2691 channel_state.by_id.retain(|_, channel| {
2692 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2693 if let Ok(Some(funding_locked)) = chan_res {
2694 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2695 node_id: channel.get_their_node_id(),
2696 msg: funding_locked,
2698 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2699 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2700 node_id: channel.get_their_node_id(),
2701 msg: announcement_sigs,
2704 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2705 } else if let Err(e) = chan_res {
2706 pending_msg_events.push(events::MessageSendEvent::HandleError {
2707 node_id: channel.get_their_node_id(),
2708 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2712 if let Some(funding_txo) = channel.get_funding_txo() {
2713 for tx in txn_matched {
2714 for inp in tx.input.iter() {
2715 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2716 if let Some(short_id) = channel.get_short_channel_id() {
2717 short_to_id.remove(&short_id);
2719 // It looks like our counterparty went on-chain. We go ahead and
2720 // broadcast our latest local state as well here, just in case its
2721 // some kind of SPV attack, though we expect these to be dropped.
2722 failed_channels.push(channel.force_shutdown());
2723 if let Ok(update) = self.get_channel_update(&channel) {
2724 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2733 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2734 if let Some(short_id) = channel.get_short_channel_id() {
2735 short_to_id.remove(&short_id);
2737 failed_channels.push(channel.force_shutdown());
2738 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2739 // the latest local tx for us, so we should skip that here (it doesn't really
2740 // hurt anything, but does make tests a bit simpler).
2741 failed_channels.last_mut().unwrap().0 = Vec::new();
2742 if let Ok(update) = self.get_channel_update(&channel) {
2743 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2752 for failure in failed_channels.drain(..) {
2753 self.finish_force_close_channel(failure);
2755 self.latest_block_height.store(height as usize, Ordering::Release);
2756 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2759 /// We force-close the channel without letting our counterparty participate in the shutdown
2760 fn block_disconnected(&self, header: &BlockHeader) {
2761 let _ = self.total_consistency_lock.read().unwrap();
2762 let mut failed_channels = Vec::new();
2764 let mut channel_lock = self.channel_state.lock().unwrap();
2765 let channel_state = channel_lock.borrow_parts();
2766 let short_to_id = channel_state.short_to_id;
2767 let pending_msg_events = channel_state.pending_msg_events;
2768 channel_state.by_id.retain(|_, v| {
2769 if v.block_disconnected(header) {
2770 if let Some(short_id) = v.get_short_channel_id() {
2771 short_to_id.remove(&short_id);
2773 failed_channels.push(v.force_shutdown());
2774 if let Ok(update) = self.get_channel_update(&v) {
2775 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2785 for failure in failed_channels.drain(..) {
2786 self.finish_force_close_channel(failure);
2788 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2789 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2793 impl ChannelMessageHandler for ChannelManager {
2794 //TODO: Handle errors and close channel (or so)
2795 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2796 let _ = self.total_consistency_lock.read().unwrap();
2797 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2800 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2801 let _ = self.total_consistency_lock.read().unwrap();
2802 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2805 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2806 let _ = self.total_consistency_lock.read().unwrap();
2807 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2810 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2811 let _ = self.total_consistency_lock.read().unwrap();
2812 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2815 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2816 let _ = self.total_consistency_lock.read().unwrap();
2817 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2820 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2821 let _ = self.total_consistency_lock.read().unwrap();
2822 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2825 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2826 let _ = self.total_consistency_lock.read().unwrap();
2827 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2830 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2831 let _ = self.total_consistency_lock.read().unwrap();
2832 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2835 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2836 let _ = self.total_consistency_lock.read().unwrap();
2837 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2840 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2841 let _ = self.total_consistency_lock.read().unwrap();
2842 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2845 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2846 let _ = self.total_consistency_lock.read().unwrap();
2847 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2850 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2851 let _ = self.total_consistency_lock.read().unwrap();
2852 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2855 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2856 let _ = self.total_consistency_lock.read().unwrap();
2857 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2860 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2861 let _ = self.total_consistency_lock.read().unwrap();
2862 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2865 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2866 let _ = self.total_consistency_lock.read().unwrap();
2867 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2870 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2871 let _ = self.total_consistency_lock.read().unwrap();
2872 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2875 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2876 let _ = self.total_consistency_lock.read().unwrap();
2877 let mut failed_channels = Vec::new();
2878 let mut failed_payments = Vec::new();
2880 let mut channel_state_lock = self.channel_state.lock().unwrap();
2881 let channel_state = channel_state_lock.borrow_parts();
2882 let short_to_id = channel_state.short_to_id;
2883 let pending_msg_events = channel_state.pending_msg_events;
2884 if no_connection_possible {
2885 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2886 channel_state.by_id.retain(|_, chan| {
2887 if chan.get_their_node_id() == *their_node_id {
2888 if let Some(short_id) = chan.get_short_channel_id() {
2889 short_to_id.remove(&short_id);
2891 failed_channels.push(chan.force_shutdown());
2892 if let Ok(update) = self.get_channel_update(&chan) {
2893 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2903 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2904 channel_state.by_id.retain(|_, chan| {
2905 if chan.get_their_node_id() == *their_node_id {
2906 //TODO: mark channel disabled (and maybe announce such after a timeout).
2907 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2908 if !failed_adds.is_empty() {
2909 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
2910 failed_payments.push((chan_update, failed_adds));
2912 if chan.is_shutdown() {
2913 if let Some(short_id) = chan.get_short_channel_id() {
2914 short_to_id.remove(&short_id);
2923 for failure in failed_channels.drain(..) {
2924 self.finish_force_close_channel(failure);
2926 for (chan_update, mut htlc_sources) in failed_payments {
2927 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2928 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2933 fn peer_connected(&self, their_node_id: &PublicKey) {
2934 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2936 let _ = self.total_consistency_lock.read().unwrap();
2937 let mut channel_state_lock = self.channel_state.lock().unwrap();
2938 let channel_state = channel_state_lock.borrow_parts();
2939 let pending_msg_events = channel_state.pending_msg_events;
2940 channel_state.by_id.retain(|_, chan| {
2941 if chan.get_their_node_id() == *their_node_id {
2942 if !chan.have_received_message() {
2943 // If we created this (outbound) channel while we were disconnected from the
2944 // peer we probably failed to send the open_channel message, which is now
2945 // lost. We can't have had anything pending related to this channel, so we just
2949 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2950 node_id: chan.get_their_node_id(),
2951 msg: chan.get_channel_reestablish(),
2957 //TODO: Also re-broadcast announcement_signatures
2960 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2961 let _ = self.total_consistency_lock.read().unwrap();
2963 if msg.channel_id == [0; 32] {
2964 for chan in self.list_channels() {
2965 if chan.remote_network_id == *their_node_id {
2966 self.force_close_channel(&chan.channel_id);
2970 self.force_close_channel(&msg.channel_id);
2975 const SERIALIZATION_VERSION: u8 = 1;
2976 const MIN_SERIALIZATION_VERSION: u8 = 1;
2978 impl Writeable for PendingForwardHTLCInfo {
2979 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2980 if let &Some(ref onion) = &self.onion_packet {
2982 onion.write(writer)?;
2986 self.incoming_shared_secret.write(writer)?;
2987 self.payment_hash.write(writer)?;
2988 self.short_channel_id.write(writer)?;
2989 self.amt_to_forward.write(writer)?;
2990 self.outgoing_cltv_value.write(writer)?;
2995 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2996 fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2997 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2999 1 => Some(msgs::OnionPacket::read(reader)?),
3000 _ => return Err(DecodeError::InvalidValue),
3002 Ok(PendingForwardHTLCInfo {
3004 incoming_shared_secret: Readable::read(reader)?,
3005 payment_hash: Readable::read(reader)?,
3006 short_channel_id: Readable::read(reader)?,
3007 amt_to_forward: Readable::read(reader)?,
3008 outgoing_cltv_value: Readable::read(reader)?,
3013 impl Writeable for HTLCFailureMsg {
3014 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3016 &HTLCFailureMsg::Relay(ref fail_msg) => {
3018 fail_msg.write(writer)?;
3020 &HTLCFailureMsg::Malformed(ref fail_msg) => {
3022 fail_msg.write(writer)?;
3029 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3030 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3031 match <u8 as Readable<R>>::read(reader)? {
3032 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3033 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3034 _ => Err(DecodeError::InvalidValue),
3039 impl Writeable for PendingHTLCStatus {
3040 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3042 &PendingHTLCStatus::Forward(ref forward_info) => {
3044 forward_info.write(writer)?;
3046 &PendingHTLCStatus::Fail(ref fail_msg) => {
3048 fail_msg.write(writer)?;
3055 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3056 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3057 match <u8 as Readable<R>>::read(reader)? {
3058 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3059 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3060 _ => Err(DecodeError::InvalidValue),
3065 impl_writeable!(HTLCPreviousHopData, 0, {
3068 incoming_packet_shared_secret
3071 impl Writeable for HTLCSource {
3072 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3074 &HTLCSource::PreviousHopData(ref hop_data) => {
3076 hop_data.write(writer)?;
3078 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3080 route.write(writer)?;
3081 session_priv.write(writer)?;
3082 first_hop_htlc_msat.write(writer)?;
3089 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3090 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3091 match <u8 as Readable<R>>::read(reader)? {
3092 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3093 1 => Ok(HTLCSource::OutboundRoute {
3094 route: Readable::read(reader)?,
3095 session_priv: Readable::read(reader)?,
3096 first_hop_htlc_msat: Readable::read(reader)?,
3098 _ => Err(DecodeError::InvalidValue),
3103 impl Writeable for HTLCFailReason {
3104 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3106 &HTLCFailReason::ErrorPacket { ref err } => {
3110 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3112 failure_code.write(writer)?;
3113 data.write(writer)?;
3120 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3121 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3122 match <u8 as Readable<R>>::read(reader)? {
3123 0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3124 1 => Ok(HTLCFailReason::Reason {
3125 failure_code: Readable::read(reader)?,
3126 data: Readable::read(reader)?,
3128 _ => Err(DecodeError::InvalidValue),
3133 impl_writeable!(HTLCForwardInfo, 0, {
3134 prev_short_channel_id,
3139 impl Writeable for ChannelManager {
3140 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3141 let _ = self.total_consistency_lock.write().unwrap();
3143 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3144 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3146 self.genesis_hash.write(writer)?;
3147 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3148 self.last_block_hash.lock().unwrap().write(writer)?;
3150 let channel_state = self.channel_state.lock().unwrap();
3151 let mut unfunded_channels = 0;
3152 for (_, channel) in channel_state.by_id.iter() {
3153 if !channel.is_funding_initiated() {
3154 unfunded_channels += 1;
3157 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3158 for (_, channel) in channel_state.by_id.iter() {
3159 if channel.is_funding_initiated() {
3160 channel.write(writer)?;
3164 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3165 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3166 short_channel_id.write(writer)?;
3167 (pending_forwards.len() as u64).write(writer)?;
3168 for forward in pending_forwards {
3169 forward.write(writer)?;
3173 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3174 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3175 payment_hash.write(writer)?;
3176 (previous_hops.len() as u64).write(writer)?;
3177 for previous_hop in previous_hops {
3178 previous_hop.write(writer)?;
3186 /// Arguments for the creation of a ChannelManager that are not deserialized.
3188 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3190 /// 1) Deserialize all stored ChannelMonitors.
3191 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3192 /// ChannelManager)>::read(reader, args).
3193 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3194 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3195 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3196 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3197 /// 4) Reconnect blocks on your ChannelMonitors.
3198 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3199 /// 6) Disconnect/connect blocks on the ChannelManager.
3200 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3201 /// automatically as it does in ChannelManager::new()).
3202 pub struct ChannelManagerReadArgs<'a> {
3203 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3204 /// deserialization.
3205 pub keys_manager: Arc<KeysInterface>,
3207 /// The fee_estimator for use in the ChannelManager in the future.
3209 /// No calls to the FeeEstimator will be made during deserialization.
3210 pub fee_estimator: Arc<FeeEstimator>,
3211 /// The ManyChannelMonitor for use in the ChannelManager in the future.
3213 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3214 /// you have deserialized ChannelMonitors separately and will add them to your
3215 /// ManyChannelMonitor after deserializing this ChannelManager.
3216 pub monitor: Arc<ManyChannelMonitor>,
3217 /// The ChainWatchInterface for use in the ChannelManager in the future.
3219 /// No calls to the ChainWatchInterface will be made during deserialization.
3220 pub chain_monitor: Arc<ChainWatchInterface>,
3221 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3222 /// used to broadcast the latest local commitment transactions of channels which must be
3223 /// force-closed during deserialization.
3224 pub tx_broadcaster: Arc<BroadcasterInterface>,
3225 /// The Logger for use in the ChannelManager and which may be used to log information during
3226 /// deserialization.
3227 pub logger: Arc<Logger>,
3228 /// Default settings used for new channels. Any existing channels will continue to use the
3229 /// runtime settings which were stored when the ChannelManager was serialized.
3230 pub default_config: UserConfig,
3232 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3233 /// value.get_funding_txo() should be the key).
3235 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3236 /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3237 /// is true for missing channels as well. If there is a monitor missing for which we find
3238 /// channel data Err(DecodeError::InvalidValue) will be returned.
3240 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3242 pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3245 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3246 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3247 let _ver: u8 = Readable::read(reader)?;
3248 let min_ver: u8 = Readable::read(reader)?;
3249 if min_ver > SERIALIZATION_VERSION {
3250 return Err(DecodeError::UnknownVersion);
3253 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3254 let latest_block_height: u32 = Readable::read(reader)?;
3255 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3257 let mut closed_channels = Vec::new();
3259 let channel_count: u64 = Readable::read(reader)?;
3260 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3261 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3262 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3263 for _ in 0..channel_count {
3264 let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3265 if channel.last_block_connected != last_block_hash {
3266 return Err(DecodeError::InvalidValue);
3269 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3270 funding_txo_set.insert(funding_txo.clone());
3271 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3272 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3273 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3274 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3275 let mut force_close_res = channel.force_shutdown();
3276 force_close_res.0 = monitor.get_latest_local_commitment_txn();
3277 closed_channels.push(force_close_res);
3279 if let Some(short_channel_id) = channel.get_short_channel_id() {
3280 short_to_id.insert(short_channel_id, channel.channel_id());
3282 by_id.insert(channel.channel_id(), channel);
3285 return Err(DecodeError::InvalidValue);
3289 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3290 if !funding_txo_set.contains(funding_txo) {
3291 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3295 let forward_htlcs_count: u64 = Readable::read(reader)?;
3296 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3297 for _ in 0..forward_htlcs_count {
3298 let short_channel_id = Readable::read(reader)?;
3299 let pending_forwards_count: u64 = Readable::read(reader)?;
3300 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3301 for _ in 0..pending_forwards_count {
3302 pending_forwards.push(Readable::read(reader)?);
3304 forward_htlcs.insert(short_channel_id, pending_forwards);
3307 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3308 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3309 for _ in 0..claimable_htlcs_count {
3310 let payment_hash = Readable::read(reader)?;
3311 let previous_hops_len: u64 = Readable::read(reader)?;
3312 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3313 for _ in 0..previous_hops_len {
3314 previous_hops.push(Readable::read(reader)?);
3316 claimable_htlcs.insert(payment_hash, previous_hops);
3319 let channel_manager = ChannelManager {
3321 fee_estimator: args.fee_estimator,
3322 monitor: args.monitor,
3323 chain_monitor: args.chain_monitor,
3324 tx_broadcaster: args.tx_broadcaster,
3326 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3327 last_block_hash: Mutex::new(last_block_hash),
3328 secp_ctx: Secp256k1::new(),
3330 channel_state: Mutex::new(ChannelHolder {
3333 next_forward: Instant::now(),
3336 pending_msg_events: Vec::new(),
3338 our_network_key: args.keys_manager.get_node_secret(),
3340 pending_events: Mutex::new(Vec::new()),
3341 total_consistency_lock: RwLock::new(()),
3342 keys_manager: args.keys_manager,
3343 logger: args.logger,
3344 default_configuration: args.default_config,
3347 for close_res in closed_channels.drain(..) {
3348 channel_manager.finish_force_close_channel(close_res);
3349 //TODO: Broadcast channel update for closed channels, but only after we've made a
3350 //connection or two.
3353 Ok((last_block_hash.clone(), channel_manager))
3359 use chain::chaininterface;
3360 use chain::transaction::OutPoint;
3361 use chain::chaininterface::{ChainListener, ChainWatchInterface};
3362 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3363 use chain::keysinterface;
3364 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3365 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3366 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3367 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3368 use ln::router::{Route, RouteHop, Router};
3370 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3371 use util::test_utils;
3372 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3373 use util::errors::APIError;
3374 use util::logger::Logger;
3375 use util::ser::{Writeable, Writer, ReadableArgs};
3376 use util::config::UserConfig;
3378 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3379 use bitcoin::util::bip143;
3380 use bitcoin::util::address::Address;
3381 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3382 use bitcoin::blockdata::block::{Block, BlockHeader};
3383 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3384 use bitcoin::blockdata::script::{Builder, Script};
3385 use bitcoin::blockdata::opcodes;
3386 use bitcoin::blockdata::constants::genesis_block;
3387 use bitcoin::network::constants::Network;
3391 use secp256k1::{Secp256k1, Message};
3392 use secp256k1::key::{PublicKey,SecretKey};
3394 use crypto::sha2::Sha256;
3395 use crypto::digest::Digest;
3397 use rand::{thread_rng,Rng};
3399 use std::cell::RefCell;
3400 use std::collections::{BTreeSet, HashMap, HashSet};
3401 use std::default::Default;
3403 use std::sync::{Arc, Mutex};
3404 use std::sync::atomic::Ordering;
3405 use std::time::Instant;
3408 fn build_test_onion_keys() -> Vec<OnionKeys> {
3409 // Keys from BOLT 4, used in both test vector tests
3410 let secp_ctx = Secp256k1::new();
3415 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3416 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3419 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3420 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3423 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3424 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3427 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3428 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3431 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3432 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3437 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3439 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3440 assert_eq!(onion_keys.len(), route.hops.len());
3445 fn onion_vectors() {
3446 // Packet creation test vectors from BOLT 4
3447 let onion_keys = build_test_onion_keys();
3449 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3450 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3451 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3452 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3453 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3455 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3456 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3457 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3458 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3459 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3461 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3462 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3463 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3464 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3465 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3467 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3468 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3469 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3470 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3471 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3473 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3474 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3475 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3476 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3477 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3479 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3480 let payloads = vec!(
3481 msgs::OnionHopData {
3483 data: msgs::OnionRealm0HopData {
3484 short_channel_id: 0,
3486 outgoing_cltv_value: 0,
3490 msgs::OnionHopData {
3492 data: msgs::OnionRealm0HopData {
3493 short_channel_id: 0x0101010101010101,
3494 amt_to_forward: 0x0100000001,
3495 outgoing_cltv_value: 0,
3499 msgs::OnionHopData {
3501 data: msgs::OnionRealm0HopData {
3502 short_channel_id: 0x0202020202020202,
3503 amt_to_forward: 0x0200000002,
3504 outgoing_cltv_value: 0,
3508 msgs::OnionHopData {
3510 data: msgs::OnionRealm0HopData {
3511 short_channel_id: 0x0303030303030303,
3512 amt_to_forward: 0x0300000003,
3513 outgoing_cltv_value: 0,
3517 msgs::OnionHopData {
3519 data: msgs::OnionRealm0HopData {
3520 short_channel_id: 0x0404040404040404,
3521 amt_to_forward: 0x0400000004,
3522 outgoing_cltv_value: 0,
3528 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3529 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3531 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3535 fn test_failure_packet_onion() {
3536 // Returning Errors test vectors from BOLT 4
3538 let onion_keys = build_test_onion_keys();
3539 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3540 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3542 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3543 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3545 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3546 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3548 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3549 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3551 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3552 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3554 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3555 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3558 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3559 assert!(chain.does_match_tx(tx));
3560 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3561 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3563 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3564 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3569 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3570 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3571 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3572 node: Arc<ChannelManager>,
3574 node_seed: [u8; 32],
3575 network_payment_count: Rc<RefCell<u8>>,
3576 network_chan_count: Rc<RefCell<u32>>,
3578 impl Drop for Node {
3579 fn drop(&mut self) {
3580 if !::std::thread::panicking() {
3581 // Check that we processed all pending events
3582 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3583 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3584 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3589 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3590 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3593 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) {
3594 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3595 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3596 (announcement, as_update, bs_update, channel_id, tx)
3599 macro_rules! get_revoke_commit_msgs {
3600 ($node: expr, $node_id: expr) => {
3602 let events = $node.node.get_and_clear_pending_msg_events();
3603 assert_eq!(events.len(), 2);
3605 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3606 assert_eq!(*node_id, $node_id);
3609 _ => panic!("Unexpected event"),
3610 }, match events[1] {
3611 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3612 assert_eq!(*node_id, $node_id);
3613 assert!(updates.update_add_htlcs.is_empty());
3614 assert!(updates.update_fulfill_htlcs.is_empty());
3615 assert!(updates.update_fail_htlcs.is_empty());
3616 assert!(updates.update_fail_malformed_htlcs.is_empty());
3617 assert!(updates.update_fee.is_none());
3618 updates.commitment_signed.clone()
3620 _ => panic!("Unexpected event"),
3626 macro_rules! get_event_msg {
3627 ($node: expr, $event_type: path, $node_id: expr) => {
3629 let events = $node.node.get_and_clear_pending_msg_events();
3630 assert_eq!(events.len(), 1);
3632 $event_type { ref node_id, ref msg } => {
3633 assert_eq!(*node_id, $node_id);
3636 _ => panic!("Unexpected event"),
3642 macro_rules! get_htlc_update_msgs {
3643 ($node: expr, $node_id: expr) => {
3645 let events = $node.node.get_and_clear_pending_msg_events();
3646 assert_eq!(events.len(), 1);
3648 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3649 assert_eq!(*node_id, $node_id);
3652 _ => panic!("Unexpected event"),
3658 macro_rules! get_feerate {
3659 ($node: expr, $channel_id: expr) => {
3661 let chan_lock = $node.node.channel_state.lock().unwrap();
3662 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3669 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3670 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3671 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();
3672 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();
3674 let chan_id = *node_a.network_chan_count.borrow();
3678 let events_2 = node_a.node.get_and_clear_pending_events();
3679 assert_eq!(events_2.len(), 1);
3681 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3682 assert_eq!(*channel_value_satoshis, channel_value);
3683 assert_eq!(user_channel_id, 42);
3685 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3686 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3688 funding_output = OutPoint::new(tx.txid(), 0);
3690 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3691 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3692 assert_eq!(added_monitors.len(), 1);
3693 assert_eq!(added_monitors[0].0, funding_output);
3694 added_monitors.clear();
3696 _ => panic!("Unexpected event"),
3699 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();
3701 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3702 assert_eq!(added_monitors.len(), 1);
3703 assert_eq!(added_monitors[0].0, funding_output);
3704 added_monitors.clear();
3707 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();
3709 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3710 assert_eq!(added_monitors.len(), 1);
3711 assert_eq!(added_monitors[0].0, funding_output);
3712 added_monitors.clear();
3715 let events_4 = node_a.node.get_and_clear_pending_events();
3716 assert_eq!(events_4.len(), 1);
3718 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3719 assert_eq!(user_channel_id, 42);
3720 assert_eq!(*funding_txo, funding_output);
3722 _ => panic!("Unexpected event"),
3728 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3729 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3730 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();
3734 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3735 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3736 assert_eq!(events_6.len(), 2);
3737 ((match events_6[0] {
3738 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3739 channel_id = msg.channel_id.clone();
3740 assert_eq!(*node_id, node_b.node.get_our_node_id());
3743 _ => panic!("Unexpected event"),
3744 }, match events_6[1] {
3745 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3746 assert_eq!(*node_id, node_b.node.get_our_node_id());
3749 _ => panic!("Unexpected event"),
3753 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) {
3754 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3755 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3759 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) {
3760 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3761 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3762 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3764 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3765 assert_eq!(events_7.len(), 1);
3766 let (announcement, bs_update) = match events_7[0] {
3767 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3770 _ => panic!("Unexpected event"),
3773 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3774 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3775 assert_eq!(events_8.len(), 1);
3776 let as_update = match events_8[0] {
3777 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3778 assert!(*announcement == *msg);
3781 _ => panic!("Unexpected event"),
3784 *node_a.network_chan_count.borrow_mut() += 1;
3786 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3789 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3790 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3793 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) {
3794 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3796 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3797 node.router.handle_channel_update(&chan_announcement.1).unwrap();
3798 node.router.handle_channel_update(&chan_announcement.2).unwrap();
3800 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3803 macro_rules! check_spends {
3804 ($tx: expr, $spends_tx: expr) => {
3806 let mut funding_tx_map = HashMap::new();
3807 let spends_tx = $spends_tx;
3808 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3809 $tx.verify(&funding_tx_map).unwrap();
3814 macro_rules! get_closing_signed_broadcast {
3815 ($node: expr, $dest_pubkey: expr) => {
3817 let events = $node.get_and_clear_pending_msg_events();
3818 assert!(events.len() == 1 || events.len() == 2);
3819 (match events[events.len() - 1] {
3820 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3821 assert_eq!(msg.contents.flags & 2, 2);
3824 _ => panic!("Unexpected event"),
3825 }, if events.len() == 2 {
3827 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3828 assert_eq!(*node_id, $dest_pubkey);
3831 _ => panic!("Unexpected event"),
3838 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) {
3839 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) };
3840 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3843 node_a.close_channel(channel_id).unwrap();
3844 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3846 let events_1 = node_b.get_and_clear_pending_msg_events();
3847 assert!(events_1.len() >= 1);
3848 let shutdown_b = match events_1[0] {
3849 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3850 assert_eq!(node_id, &node_a.get_our_node_id());
3853 _ => panic!("Unexpected event"),
3856 let closing_signed_b = if !close_inbound_first {
3857 assert_eq!(events_1.len(), 1);
3860 Some(match events_1[1] {
3861 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3862 assert_eq!(node_id, &node_a.get_our_node_id());
3865 _ => panic!("Unexpected event"),
3869 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3870 let (as_update, bs_update) = if close_inbound_first {
3871 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3872 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3873 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3874 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3875 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3877 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3878 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3879 assert!(none_b.is_none());
3880 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3881 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3882 (as_update, bs_update)
3884 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3886 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3887 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3888 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3889 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3891 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3892 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3893 assert!(none_a.is_none());
3894 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3895 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3896 (as_update, bs_update)
3898 assert_eq!(tx_a, tx_b);
3899 check_spends!(tx_a, funding_tx);
3901 (as_update, bs_update, tx_a)
3906 msgs: Vec<msgs::UpdateAddHTLC>,
3907 commitment_msg: msgs::CommitmentSigned,
3910 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3911 assert!(updates.update_fulfill_htlcs.is_empty());
3912 assert!(updates.update_fail_htlcs.is_empty());
3913 assert!(updates.update_fail_malformed_htlcs.is_empty());
3914 assert!(updates.update_fee.is_none());
3915 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3918 fn from_event(event: MessageSendEvent) -> SendEvent {
3920 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3921 _ => panic!("Unexpected event type!"),
3925 fn from_node(node: &Node) -> SendEvent {
3926 let mut events = node.node.get_and_clear_pending_msg_events();
3927 assert_eq!(events.len(), 1);
3928 SendEvent::from_event(events.pop().unwrap())
3932 macro_rules! check_added_monitors {
3933 ($node: expr, $count: expr) => {
3935 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3936 assert_eq!(added_monitors.len(), $count);
3937 added_monitors.clear();
3942 macro_rules! commitment_signed_dance {
3943 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3945 check_added_monitors!($node_a, 0);
3946 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3947 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3948 check_added_monitors!($node_a, 1);
3949 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3952 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3954 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3955 check_added_monitors!($node_b, 0);
3956 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3957 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3958 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3959 check_added_monitors!($node_b, 1);
3960 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3961 let (bs_revoke_and_ack, extra_msg_option) = {
3962 let events = $node_b.node.get_and_clear_pending_msg_events();
3963 assert!(events.len() <= 2);
3965 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3966 assert_eq!(*node_id, $node_a.node.get_our_node_id());
3969 _ => panic!("Unexpected event"),
3970 }, events.get(1).map(|e| e.clone()))
3972 check_added_monitors!($node_b, 1);
3973 if $fail_backwards {
3974 assert!($node_a.node.get_and_clear_pending_events().is_empty());
3975 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3977 (extra_msg_option, bs_revoke_and_ack)
3980 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3982 check_added_monitors!($node_a, 0);
3983 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3984 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3985 check_added_monitors!($node_a, 1);
3986 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3987 assert!(extra_msg_option.is_none());
3991 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3993 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3994 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3996 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3997 if $fail_backwards {
3998 assert_eq!(added_monitors.len(), 2);
3999 assert!(added_monitors[0].0 != added_monitors[1].0);
4001 assert_eq!(added_monitors.len(), 1);
4003 added_monitors.clear();
4008 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4010 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4013 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4015 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4016 if $fail_backwards {
4017 let channel_state = $node_a.node.channel_state.lock().unwrap();
4018 assert_eq!(channel_state.pending_msg_events.len(), 1);
4019 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4020 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4021 } else { panic!("Unexpected event"); }
4023 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4029 macro_rules! get_payment_preimage_hash {
4032 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4033 *$node.network_payment_count.borrow_mut() += 1;
4034 let mut payment_hash = PaymentHash([0; 32]);
4035 let mut sha = Sha256::new();
4036 sha.input(&payment_preimage.0[..]);
4037 sha.result(&mut payment_hash.0[..]);
4038 (payment_preimage, payment_hash)
4043 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4044 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4046 let mut payment_event = {
4047 origin_node.node.send_payment(route, our_payment_hash).unwrap();
4048 check_added_monitors!(origin_node, 1);
4050 let mut events = origin_node.node.get_and_clear_pending_msg_events();
4051 assert_eq!(events.len(), 1);
4052 SendEvent::from_event(events.remove(0))
4054 let mut prev_node = origin_node;
4056 for (idx, &node) in expected_route.iter().enumerate() {
4057 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4059 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4060 check_added_monitors!(node, 0);
4061 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4063 let events_1 = node.node.get_and_clear_pending_events();
4064 assert_eq!(events_1.len(), 1);
4066 Event::PendingHTLCsForwardable { .. } => { },
4067 _ => panic!("Unexpected event"),
4070 node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4071 node.node.process_pending_htlc_forwards();
4073 if idx == expected_route.len() - 1 {
4074 let events_2 = node.node.get_and_clear_pending_events();
4075 assert_eq!(events_2.len(), 1);
4077 Event::PaymentReceived { ref payment_hash, amt } => {
4078 assert_eq!(our_payment_hash, *payment_hash);
4079 assert_eq!(amt, recv_value);
4081 _ => panic!("Unexpected event"),
4084 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4085 assert_eq!(events_2.len(), 1);
4086 check_added_monitors!(node, 1);
4087 payment_event = SendEvent::from_event(events_2.remove(0));
4088 assert_eq!(payment_event.msgs.len(), 1);
4094 (our_payment_preimage, our_payment_hash)
4097 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4098 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4099 check_added_monitors!(expected_route.last().unwrap(), 1);
4101 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4102 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4103 macro_rules! get_next_msgs {
4106 let events = $node.node.get_and_clear_pending_msg_events();
4107 assert_eq!(events.len(), 1);
4109 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 } } => {
4110 assert!(update_add_htlcs.is_empty());
4111 assert_eq!(update_fulfill_htlcs.len(), 1);
4112 assert!(update_fail_htlcs.is_empty());
4113 assert!(update_fail_malformed_htlcs.is_empty());
4114 assert!(update_fee.is_none());
4115 expected_next_node = node_id.clone();
4116 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4118 _ => panic!("Unexpected event"),
4124 macro_rules! last_update_fulfill_dance {
4125 ($node: expr, $prev_node: expr) => {
4127 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4128 check_added_monitors!($node, 0);
4129 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4130 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4134 macro_rules! mid_update_fulfill_dance {
4135 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4137 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4138 check_added_monitors!($node, 1);
4139 let new_next_msgs = if $new_msgs {
4140 get_next_msgs!($node)
4142 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4145 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4146 next_msgs = new_next_msgs;
4151 let mut prev_node = expected_route.last().unwrap();
4152 for (idx, node) in expected_route.iter().rev().enumerate() {
4153 assert_eq!(expected_next_node, node.node.get_our_node_id());
4154 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4155 if next_msgs.is_some() {
4156 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4157 } else if update_next_msgs {
4158 next_msgs = get_next_msgs!(node);
4160 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4162 if !skip_last && idx == expected_route.len() - 1 {
4163 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4170 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4171 let events = origin_node.node.get_and_clear_pending_events();
4172 assert_eq!(events.len(), 1);
4174 Event::PaymentSent { payment_preimage } => {
4175 assert_eq!(payment_preimage, our_payment_preimage);
4177 _ => panic!("Unexpected event"),
4182 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4183 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4186 const TEST_FINAL_CLTV: u32 = 32;
4188 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4189 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();
4190 assert_eq!(route.hops.len(), expected_route.len());
4191 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4192 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4195 send_along_route(origin_node, route, expected_route, recv_value)
4198 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4199 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();
4200 assert_eq!(route.hops.len(), expected_route.len());
4201 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4202 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4205 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4207 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4209 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4210 _ => panic!("Unknown error variants"),
4214 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4215 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4216 claim_payment(&origin, expected_route, our_payment_preimage);
4219 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4220 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4221 check_added_monitors!(expected_route.last().unwrap(), 1);
4223 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4224 macro_rules! update_fail_dance {
4225 ($node: expr, $prev_node: expr, $last_node: expr) => {
4227 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4228 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4233 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4234 let mut prev_node = expected_route.last().unwrap();
4235 for (idx, node) in expected_route.iter().rev().enumerate() {
4236 assert_eq!(expected_next_node, node.node.get_our_node_id());
4237 if next_msgs.is_some() {
4238 // We may be the "last node" for the purpose of the commitment dance if we're
4239 // skipping the last node (implying it is disconnected) and we're the
4240 // second-to-last node!
4241 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4244 let events = node.node.get_and_clear_pending_msg_events();
4245 if !skip_last || idx != expected_route.len() - 1 {
4246 assert_eq!(events.len(), 1);
4248 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 } } => {
4249 assert!(update_add_htlcs.is_empty());
4250 assert!(update_fulfill_htlcs.is_empty());
4251 assert_eq!(update_fail_htlcs.len(), 1);
4252 assert!(update_fail_malformed_htlcs.is_empty());
4253 assert!(update_fee.is_none());
4254 expected_next_node = node_id.clone();
4255 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4257 _ => panic!("Unexpected event"),
4260 assert!(events.is_empty());
4262 if !skip_last && idx == expected_route.len() - 1 {
4263 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4270 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4272 let events = origin_node.node.get_and_clear_pending_events();
4273 assert_eq!(events.len(), 1);
4275 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4276 assert_eq!(payment_hash, our_payment_hash);
4277 assert!(rejected_by_dest);
4279 _ => panic!("Unexpected event"),
4284 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4285 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4288 fn create_network(node_count: usize) -> Vec<Node> {
4289 let mut nodes = Vec::new();
4290 let mut rng = thread_rng();
4291 let secp_ctx = Secp256k1::new();
4292 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
4294 let chan_count = Rc::new(RefCell::new(0));
4295 let payment_count = Rc::new(RefCell::new(0));
4297 for _ in 0..node_count {
4298 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4299 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4300 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4301 let mut seed = [0; 32];
4302 rng.fill_bytes(&mut seed);
4303 let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4304 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4305 let mut config = UserConfig::new();
4306 config.channel_options.announced_channel = true;
4307 config.channel_limits.force_announced_channel_preference = false;
4308 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();
4309 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4310 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4311 network_payment_count: payment_count.clone(),
4312 network_chan_count: chan_count.clone(),
4320 fn test_async_inbound_update_fee() {
4321 let mut nodes = create_network(2);
4322 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4323 let channel_id = chan.2;
4326 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4330 // send (1) commitment_signed -.
4331 // <- update_add_htlc/commitment_signed
4332 // send (2) RAA (awaiting remote revoke) -.
4333 // (1) commitment_signed is delivered ->
4334 // .- send (3) RAA (awaiting remote revoke)
4335 // (2) RAA is delivered ->
4336 // .- send (4) commitment_signed
4337 // <- (3) RAA is delivered
4338 // send (5) commitment_signed -.
4339 // <- (4) commitment_signed is delivered
4341 // (5) commitment_signed is delivered ->
4343 // (6) RAA is delivered ->
4345 // First nodes[0] generates an update_fee
4346 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4347 check_added_monitors!(nodes[0], 1);
4349 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4350 assert_eq!(events_0.len(), 1);
4351 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4352 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4353 (update_fee.as_ref(), commitment_signed)
4355 _ => panic!("Unexpected event"),
4358 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4360 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4361 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4362 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();
4363 check_added_monitors!(nodes[1], 1);
4365 let payment_event = {
4366 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4367 assert_eq!(events_1.len(), 1);
4368 SendEvent::from_event(events_1.remove(0))
4370 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4371 assert_eq!(payment_event.msgs.len(), 1);
4373 // ...now when the messages get delivered everyone should be happy
4374 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4375 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4376 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4377 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4378 check_added_monitors!(nodes[0], 1);
4380 // deliver(1), generate (3):
4381 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4382 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4383 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4384 check_added_monitors!(nodes[1], 1);
4386 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4387 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4388 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4389 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4390 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4391 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4392 assert!(bs_update.update_fee.is_none()); // (4)
4393 check_added_monitors!(nodes[1], 1);
4395 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4396 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4397 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4398 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4399 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4400 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4401 assert!(as_update.update_fee.is_none()); // (5)
4402 check_added_monitors!(nodes[0], 1);
4404 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4405 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4406 // only (6) so get_event_msg's assert(len == 1) passes
4407 check_added_monitors!(nodes[0], 1);
4409 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4410 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4411 check_added_monitors!(nodes[1], 1);
4413 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4414 check_added_monitors!(nodes[0], 1);
4416 let events_2 = nodes[0].node.get_and_clear_pending_events();
4417 assert_eq!(events_2.len(), 1);
4419 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4420 _ => panic!("Unexpected event"),
4423 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4424 check_added_monitors!(nodes[1], 1);
4428 fn test_update_fee_unordered_raa() {
4429 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4430 // crash in an earlier version of the update_fee patch)
4431 let mut nodes = create_network(2);
4432 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4433 let channel_id = chan.2;
4436 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4438 // First nodes[0] generates an update_fee
4439 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4440 check_added_monitors!(nodes[0], 1);
4442 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4443 assert_eq!(events_0.len(), 1);
4444 let update_msg = match events_0[0] { // (1)
4445 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4448 _ => panic!("Unexpected event"),
4451 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4453 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4454 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4455 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();
4456 check_added_monitors!(nodes[1], 1);
4458 let payment_event = {
4459 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4460 assert_eq!(events_1.len(), 1);
4461 SendEvent::from_event(events_1.remove(0))
4463 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4464 assert_eq!(payment_event.msgs.len(), 1);
4466 // ...now when the messages get delivered everyone should be happy
4467 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4468 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4469 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4470 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4471 check_added_monitors!(nodes[0], 1);
4473 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4474 check_added_monitors!(nodes[1], 1);
4476 // We can't continue, sadly, because our (1) now has a bogus signature
4480 fn test_multi_flight_update_fee() {
4481 let nodes = create_network(2);
4482 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4483 let channel_id = chan.2;
4486 // update_fee/commitment_signed ->
4487 // .- send (1) RAA and (2) commitment_signed
4488 // update_fee (never committed) ->
4489 // (3) update_fee ->
4490 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4491 // don't track which updates correspond to which revoke_and_ack responses so we're in
4492 // AwaitingRAA mode and will not generate the update_fee yet.
4493 // <- (1) RAA delivered
4494 // (3) is generated and send (4) CS -.
4495 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4496 // know the per_commitment_point to use for it.
4497 // <- (2) commitment_signed delivered
4498 // revoke_and_ack ->
4499 // B should send no response here
4500 // (4) commitment_signed delivered ->
4501 // <- RAA/commitment_signed delivered
4502 // revoke_and_ack ->
4504 // First nodes[0] generates an update_fee
4505 let initial_feerate = get_feerate!(nodes[0], channel_id);
4506 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4507 check_added_monitors!(nodes[0], 1);
4509 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4510 assert_eq!(events_0.len(), 1);
4511 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4512 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4513 (update_fee.as_ref().unwrap(), commitment_signed)
4515 _ => panic!("Unexpected event"),
4518 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4519 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4520 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4521 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4522 check_added_monitors!(nodes[1], 1);
4524 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4526 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4527 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4528 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4530 // Create the (3) update_fee message that nodes[0] will generate before it does...
4531 let mut update_msg_2 = msgs::UpdateFee {
4532 channel_id: update_msg_1.channel_id.clone(),
4533 feerate_per_kw: (initial_feerate + 30) as u32,
4536 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4538 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4540 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4542 // Deliver (1), generating (3) and (4)
4543 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4544 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4545 check_added_monitors!(nodes[0], 1);
4546 assert!(as_second_update.update_add_htlcs.is_empty());
4547 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4548 assert!(as_second_update.update_fail_htlcs.is_empty());
4549 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4550 // Check that the update_fee newly generated matches what we delivered:
4551 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4552 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4554 // Deliver (2) commitment_signed
4555 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4556 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4557 check_added_monitors!(nodes[0], 1);
4558 // No commitment_signed so get_event_msg's assert(len == 1) passes
4560 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4561 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4562 check_added_monitors!(nodes[1], 1);
4565 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4566 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4567 check_added_monitors!(nodes[1], 1);
4569 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4570 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4571 check_added_monitors!(nodes[0], 1);
4573 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4574 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4575 // No commitment_signed so get_event_msg's assert(len == 1) passes
4576 check_added_monitors!(nodes[0], 1);
4578 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4579 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4580 check_added_monitors!(nodes[1], 1);
4584 fn test_update_fee_vanilla() {
4585 let nodes = create_network(2);
4586 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4587 let channel_id = chan.2;
4589 let feerate = get_feerate!(nodes[0], channel_id);
4590 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4591 check_added_monitors!(nodes[0], 1);
4593 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4594 assert_eq!(events_0.len(), 1);
4595 let (update_msg, commitment_signed) = match events_0[0] {
4596 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 } } => {
4597 (update_fee.as_ref(), commitment_signed)
4599 _ => panic!("Unexpected event"),
4601 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4603 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4604 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4605 check_added_monitors!(nodes[1], 1);
4607 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4608 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4609 check_added_monitors!(nodes[0], 1);
4611 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4612 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4613 // No commitment_signed so get_event_msg's assert(len == 1) passes
4614 check_added_monitors!(nodes[0], 1);
4616 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4617 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4618 check_added_monitors!(nodes[1], 1);
4622 fn test_update_fee_that_funder_cannot_afford() {
4623 let nodes = create_network(2);
4624 let channel_value = 1888;
4625 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4626 let channel_id = chan.2;
4629 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4630 check_added_monitors!(nodes[0], 1);
4631 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4633 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4635 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4637 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4638 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4640 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4641 let chan = chan_lock.by_id.get(&channel_id).unwrap();
4643 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4644 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4645 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4646 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4647 actual_fee = channel_value - actual_fee;
4648 assert_eq!(total_fee, actual_fee);
4651 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4652 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4653 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4654 check_added_monitors!(nodes[0], 1);
4656 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4658 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4660 //While producing the commitment_signed response after handling a received update_fee request the
4661 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4662 //Should produce and error.
4663 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4665 assert!(match err.err {
4666 "Funding remote cannot afford proposed new fee" => true,
4670 //clear the message we could not handle
4671 nodes[1].node.get_and_clear_pending_msg_events();
4675 fn test_update_fee_with_fundee_update_add_htlc() {
4676 let mut nodes = create_network(2);
4677 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4678 let channel_id = chan.2;
4681 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4683 let feerate = get_feerate!(nodes[0], channel_id);
4684 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4685 check_added_monitors!(nodes[0], 1);
4687 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4688 assert_eq!(events_0.len(), 1);
4689 let (update_msg, commitment_signed) = match events_0[0] {
4690 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 } } => {
4691 (update_fee.as_ref(), commitment_signed)
4693 _ => panic!("Unexpected event"),
4695 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4696 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4697 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4698 check_added_monitors!(nodes[1], 1);
4700 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4702 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4704 // nothing happens since node[1] is in AwaitingRemoteRevoke
4705 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4707 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4708 assert_eq!(added_monitors.len(), 0);
4709 added_monitors.clear();
4711 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4712 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4713 // node[1] has nothing to do
4715 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4716 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4717 check_added_monitors!(nodes[0], 1);
4719 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4720 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4721 // No commitment_signed so get_event_msg's assert(len == 1) passes
4722 check_added_monitors!(nodes[0], 1);
4723 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4724 check_added_monitors!(nodes[1], 1);
4725 // AwaitingRemoteRevoke ends here
4727 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4728 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4729 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4730 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4731 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4732 assert_eq!(commitment_update.update_fee.is_none(), true);
4734 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4735 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4736 check_added_monitors!(nodes[0], 1);
4737 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4739 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4740 check_added_monitors!(nodes[1], 1);
4741 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4743 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4744 check_added_monitors!(nodes[1], 1);
4745 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4746 // No commitment_signed so get_event_msg's assert(len == 1) passes
4748 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4749 check_added_monitors!(nodes[0], 1);
4750 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4752 let events = nodes[0].node.get_and_clear_pending_events();
4753 assert_eq!(events.len(), 1);
4755 Event::PendingHTLCsForwardable { .. } => { },
4756 _ => panic!("Unexpected event"),
4758 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4759 nodes[0].node.process_pending_htlc_forwards();
4761 let events = nodes[0].node.get_and_clear_pending_events();
4762 assert_eq!(events.len(), 1);
4764 Event::PaymentReceived { .. } => { },
4765 _ => panic!("Unexpected event"),
4768 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4770 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4771 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4772 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4776 fn test_update_fee() {
4777 let nodes = create_network(2);
4778 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4779 let channel_id = chan.2;
4782 // (1) update_fee/commitment_signed ->
4783 // <- (2) revoke_and_ack
4784 // .- send (3) commitment_signed
4785 // (4) update_fee/commitment_signed ->
4786 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4787 // <- (3) commitment_signed delivered
4788 // send (6) revoke_and_ack -.
4789 // <- (5) deliver revoke_and_ack
4790 // (6) deliver revoke_and_ack ->
4791 // .- send (7) commitment_signed in response to (4)
4792 // <- (7) deliver commitment_signed
4793 // revoke_and_ack ->
4795 // Create and deliver (1)...
4796 let feerate = get_feerate!(nodes[0], channel_id);
4797 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4798 check_added_monitors!(nodes[0], 1);
4800 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4801 assert_eq!(events_0.len(), 1);
4802 let (update_msg, commitment_signed) = match events_0[0] {
4803 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 } } => {
4804 (update_fee.as_ref(), commitment_signed)
4806 _ => panic!("Unexpected event"),
4808 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4810 // Generate (2) and (3):
4811 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4812 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4813 check_added_monitors!(nodes[1], 1);
4816 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4817 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4818 check_added_monitors!(nodes[0], 1);
4820 // Create and deliver (4)...
4821 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4822 check_added_monitors!(nodes[0], 1);
4823 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4824 assert_eq!(events_0.len(), 1);
4825 let (update_msg, commitment_signed) = match events_0[0] {
4826 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 } } => {
4827 (update_fee.as_ref(), commitment_signed)
4829 _ => panic!("Unexpected event"),
4832 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4833 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4834 check_added_monitors!(nodes[1], 1);
4836 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4837 // No commitment_signed so get_event_msg's assert(len == 1) passes
4839 // Handle (3), creating (6):
4840 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4841 check_added_monitors!(nodes[0], 1);
4842 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4843 // No commitment_signed so get_event_msg's assert(len == 1) passes
4846 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4847 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4848 check_added_monitors!(nodes[0], 1);
4850 // Deliver (6), creating (7):
4851 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4852 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4853 assert!(commitment_update.update_add_htlcs.is_empty());
4854 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4855 assert!(commitment_update.update_fail_htlcs.is_empty());
4856 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4857 assert!(commitment_update.update_fee.is_none());
4858 check_added_monitors!(nodes[1], 1);
4861 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4862 check_added_monitors!(nodes[0], 1);
4863 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4864 // No commitment_signed so get_event_msg's assert(len == 1) passes
4866 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4867 check_added_monitors!(nodes[1], 1);
4868 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4870 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4871 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4872 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4876 fn pre_funding_lock_shutdown_test() {
4877 // Test sending a shutdown prior to funding_locked after funding generation
4878 let nodes = create_network(2);
4879 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4880 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4881 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4882 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4884 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4885 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4886 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4887 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4888 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4890 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4891 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4892 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4893 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4894 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4895 assert!(node_0_none.is_none());
4897 assert!(nodes[0].node.list_channels().is_empty());
4898 assert!(nodes[1].node.list_channels().is_empty());
4902 fn updates_shutdown_wait() {
4903 // Test sending a shutdown with outstanding updates pending
4904 let mut nodes = create_network(3);
4905 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4906 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4907 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4908 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4910 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4912 nodes[0].node.close_channel(&chan_1.2).unwrap();
4913 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4914 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4915 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4916 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4918 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4919 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4921 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4922 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4923 else { panic!("New sends should fail!") };
4924 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4925 else { panic!("New sends should fail!") };
4927 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4928 check_added_monitors!(nodes[2], 1);
4929 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4930 assert!(updates.update_add_htlcs.is_empty());
4931 assert!(updates.update_fail_htlcs.is_empty());
4932 assert!(updates.update_fail_malformed_htlcs.is_empty());
4933 assert!(updates.update_fee.is_none());
4934 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4935 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4936 check_added_monitors!(nodes[1], 1);
4937 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4938 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4940 assert!(updates_2.update_add_htlcs.is_empty());
4941 assert!(updates_2.update_fail_htlcs.is_empty());
4942 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4943 assert!(updates_2.update_fee.is_none());
4944 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4945 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4946 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4948 let events = nodes[0].node.get_and_clear_pending_events();
4949 assert_eq!(events.len(), 1);
4951 Event::PaymentSent { ref payment_preimage } => {
4952 assert_eq!(our_payment_preimage, *payment_preimage);
4954 _ => panic!("Unexpected event"),
4957 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4958 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4959 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4960 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4961 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4962 assert!(node_0_none.is_none());
4964 assert!(nodes[0].node.list_channels().is_empty());
4966 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4967 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4968 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4969 assert!(nodes[1].node.list_channels().is_empty());
4970 assert!(nodes[2].node.list_channels().is_empty());
4974 fn htlc_fail_async_shutdown() {
4975 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4976 let mut nodes = create_network(3);
4977 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4978 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4980 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4981 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4982 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4983 check_added_monitors!(nodes[0], 1);
4984 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4985 assert_eq!(updates.update_add_htlcs.len(), 1);
4986 assert!(updates.update_fulfill_htlcs.is_empty());
4987 assert!(updates.update_fail_htlcs.is_empty());
4988 assert!(updates.update_fail_malformed_htlcs.is_empty());
4989 assert!(updates.update_fee.is_none());
4991 nodes[1].node.close_channel(&chan_1.2).unwrap();
4992 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4993 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4994 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4996 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4997 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4998 check_added_monitors!(nodes[1], 1);
4999 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5000 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5002 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5003 assert!(updates_2.update_add_htlcs.is_empty());
5004 assert!(updates_2.update_fulfill_htlcs.is_empty());
5005 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5006 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5007 assert!(updates_2.update_fee.is_none());
5009 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5010 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5012 let events = nodes[0].node.get_and_clear_pending_events();
5013 assert_eq!(events.len(), 1);
5015 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
5016 assert_eq!(our_payment_hash, *payment_hash);
5017 assert!(!rejected_by_dest);
5019 _ => panic!("Unexpected event"),
5022 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5023 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5024 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5025 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5026 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5027 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5028 assert!(node_0_none.is_none());
5030 assert!(nodes[0].node.list_channels().is_empty());
5032 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5033 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5034 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5035 assert!(nodes[1].node.list_channels().is_empty());
5036 assert!(nodes[2].node.list_channels().is_empty());
5039 fn do_test_shutdown_rebroadcast(recv_count: u8) {
5040 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5041 // messages delivered prior to disconnect
5042 let nodes = create_network(3);
5043 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5044 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5046 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5048 nodes[1].node.close_channel(&chan_1.2).unwrap();
5049 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5051 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5052 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5054 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5058 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5059 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5061 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5062 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5063 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5064 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5066 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5067 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5068 assert!(node_1_shutdown == node_1_2nd_shutdown);
5070 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5071 let node_0_2nd_shutdown = if recv_count > 0 {
5072 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5073 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5076 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5077 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5078 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5080 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5082 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5083 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5085 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5086 check_added_monitors!(nodes[2], 1);
5087 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5088 assert!(updates.update_add_htlcs.is_empty());
5089 assert!(updates.update_fail_htlcs.is_empty());
5090 assert!(updates.update_fail_malformed_htlcs.is_empty());
5091 assert!(updates.update_fee.is_none());
5092 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5093 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5094 check_added_monitors!(nodes[1], 1);
5095 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5096 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5098 assert!(updates_2.update_add_htlcs.is_empty());
5099 assert!(updates_2.update_fail_htlcs.is_empty());
5100 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5101 assert!(updates_2.update_fee.is_none());
5102 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5103 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5104 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5106 let events = nodes[0].node.get_and_clear_pending_events();
5107 assert_eq!(events.len(), 1);
5109 Event::PaymentSent { ref payment_preimage } => {
5110 assert_eq!(our_payment_preimage, *payment_preimage);
5112 _ => panic!("Unexpected event"),
5115 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5117 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5118 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5119 assert!(node_1_closing_signed.is_some());
5122 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5123 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5125 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5126 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5127 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5128 if recv_count == 0 {
5129 // If all closing_signeds weren't delivered we can just resume where we left off...
5130 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5132 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5133 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5134 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5136 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5137 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5138 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5140 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5141 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5143 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5144 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5145 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5147 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5148 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5149 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5150 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5151 assert!(node_0_none.is_none());
5153 // If one node, however, received + responded with an identical closing_signed we end
5154 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5155 // There isn't really anything better we can do simply, but in the future we might
5156 // explore storing a set of recently-closed channels that got disconnected during
5157 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5158 // give our counterparty enough time to (potentially) broadcast a cooperative closing
5160 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5162 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5163 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5164 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5165 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5166 assert_eq!(*channel_id, chan_1.2);
5167 } else { panic!("Needed SendErrorMessage close"); }
5169 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5170 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5171 // closing_signed so we do it ourselves
5172 let events = nodes[0].node.get_and_clear_pending_msg_events();
5173 assert_eq!(events.len(), 1);
5175 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5176 assert_eq!(msg.contents.flags & 2, 2);
5178 _ => panic!("Unexpected event"),
5182 assert!(nodes[0].node.list_channels().is_empty());
5184 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5185 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5186 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5187 assert!(nodes[1].node.list_channels().is_empty());
5188 assert!(nodes[2].node.list_channels().is_empty());
5192 fn test_shutdown_rebroadcast() {
5193 do_test_shutdown_rebroadcast(0);
5194 do_test_shutdown_rebroadcast(1);
5195 do_test_shutdown_rebroadcast(2);
5199 fn fake_network_test() {
5200 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5201 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5202 let nodes = create_network(4);
5204 // Create some initial channels
5205 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5206 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5207 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5209 // Rebalance the network a bit by relaying one payment through all the channels...
5210 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5211 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5212 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5213 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5215 // Send some more payments
5216 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5217 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5218 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5220 // Test failure packets
5221 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5222 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5224 // Add a new channel that skips 3
5225 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5227 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5228 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5229 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5230 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5231 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5232 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5233 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5235 // Do some rebalance loop payments, simultaneously
5236 let mut hops = Vec::with_capacity(3);
5237 hops.push(RouteHop {
5238 pubkey: nodes[2].node.get_our_node_id(),
5239 short_channel_id: chan_2.0.contents.short_channel_id,
5241 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5243 hops.push(RouteHop {
5244 pubkey: nodes[3].node.get_our_node_id(),
5245 short_channel_id: chan_3.0.contents.short_channel_id,
5247 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5249 hops.push(RouteHop {
5250 pubkey: nodes[1].node.get_our_node_id(),
5251 short_channel_id: chan_4.0.contents.short_channel_id,
5253 cltv_expiry_delta: TEST_FINAL_CLTV,
5255 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;
5256 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;
5257 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5259 let mut hops = Vec::with_capacity(3);
5260 hops.push(RouteHop {
5261 pubkey: nodes[3].node.get_our_node_id(),
5262 short_channel_id: chan_4.0.contents.short_channel_id,
5264 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5266 hops.push(RouteHop {
5267 pubkey: nodes[2].node.get_our_node_id(),
5268 short_channel_id: chan_3.0.contents.short_channel_id,
5270 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5272 hops.push(RouteHop {
5273 pubkey: nodes[1].node.get_our_node_id(),
5274 short_channel_id: chan_2.0.contents.short_channel_id,
5276 cltv_expiry_delta: TEST_FINAL_CLTV,
5278 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;
5279 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;
5280 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5282 // Claim the rebalances...
5283 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5284 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5286 // Add a duplicate new channel from 2 to 4
5287 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5289 // Send some payments across both channels
5290 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5291 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5292 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5294 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5296 //TODO: Test that routes work again here as we've been notified that the channel is full
5298 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5299 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5300 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5302 // Close down the channels...
5303 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5304 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5305 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5306 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5307 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5311 fn duplicate_htlc_test() {
5312 // Test that we accept duplicate payment_hash HTLCs across the network and that
5313 // claiming/failing them are all separate and don't effect each other
5314 let mut nodes = create_network(6);
5316 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5317 create_announced_chan_between_nodes(&nodes, 0, 3);
5318 create_announced_chan_between_nodes(&nodes, 1, 3);
5319 create_announced_chan_between_nodes(&nodes, 2, 3);
5320 create_announced_chan_between_nodes(&nodes, 3, 4);
5321 create_announced_chan_between_nodes(&nodes, 3, 5);
5323 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5325 *nodes[0].network_payment_count.borrow_mut() -= 1;
5326 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5328 *nodes[0].network_payment_count.borrow_mut() -= 1;
5329 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5331 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5332 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5333 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5336 #[derive(PartialEq)]
5337 enum HTLCType { NONE, TIMEOUT, SUCCESS }
5338 /// Tests that the given node has broadcast transactions for the given Channel
5340 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5341 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5342 /// broadcast and the revoked outputs were claimed.
5344 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5345 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5347 /// All broadcast transactions must be accounted for in one of the above three types of we'll
5349 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5350 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5351 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5353 let mut res = Vec::with_capacity(2);
5354 node_txn.retain(|tx| {
5355 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5356 check_spends!(tx, chan.3.clone());
5357 if commitment_tx.is_none() {
5358 res.push(tx.clone());
5363 if let Some(explicit_tx) = commitment_tx {
5364 res.push(explicit_tx.clone());
5367 assert_eq!(res.len(), 1);
5369 if has_htlc_tx != HTLCType::NONE {
5370 node_txn.retain(|tx| {
5371 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5372 check_spends!(tx, res[0].clone());
5373 if has_htlc_tx == HTLCType::TIMEOUT {
5374 assert!(tx.lock_time != 0);
5376 assert!(tx.lock_time == 0);
5378 res.push(tx.clone());
5382 assert!(res.len() == 2 || res.len() == 3);
5384 assert_eq!(res[1], res[2]);
5388 assert!(node_txn.is_empty());
5392 /// Tests that the given node has broadcast a claim transaction against the provided revoked
5393 /// HTLC transaction.
5394 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5395 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5396 assert_eq!(node_txn.len(), 1);
5397 node_txn.retain(|tx| {
5398 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5399 check_spends!(tx, revoked_tx.clone());
5403 assert!(node_txn.is_empty());
5406 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5407 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5409 assert!(node_txn.len() >= 1);
5410 assert_eq!(node_txn[0].input.len(), 1);
5411 let mut found_prev = false;
5413 for tx in prev_txn {
5414 if node_txn[0].input[0].previous_output.txid == tx.txid() {
5415 check_spends!(node_txn[0], tx.clone());
5416 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5417 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5423 assert!(found_prev);
5425 let mut res = Vec::new();
5426 mem::swap(&mut *node_txn, &mut res);
5430 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5431 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5432 assert_eq!(events_1.len(), 1);
5433 let as_update = match events_1[0] {
5434 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5437 _ => panic!("Unexpected event"),
5440 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5441 assert_eq!(events_2.len(), 1);
5442 let bs_update = match events_2[0] {
5443 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5446 _ => panic!("Unexpected event"),
5450 node.router.handle_channel_update(&as_update).unwrap();
5451 node.router.handle_channel_update(&bs_update).unwrap();
5455 macro_rules! expect_pending_htlcs_forwardable {
5457 let events = $node.node.get_and_clear_pending_events();
5458 assert_eq!(events.len(), 1);
5460 Event::PendingHTLCsForwardable { .. } => { },
5461 _ => panic!("Unexpected event"),
5463 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5464 $node.node.process_pending_htlc_forwards();
5468 fn do_channel_reserve_test(test_recv: bool) {
5470 use std::sync::atomic::Ordering;
5471 use ln::msgs::HandleError;
5473 macro_rules! get_channel_value_stat {
5474 ($node: expr, $channel_id: expr) => {{
5475 let chan_lock = $node.node.channel_state.lock().unwrap();
5476 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5477 chan.get_value_stat()
5481 let mut nodes = create_network(3);
5482 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5483 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5485 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5486 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5488 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5489 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5491 macro_rules! get_route_and_payment_hash {
5492 ($recv_value: expr) => {{
5493 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5494 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5495 (route, payment_hash, payment_preimage)
5499 macro_rules! expect_forward {
5501 let mut events = $node.node.get_and_clear_pending_msg_events();
5502 assert_eq!(events.len(), 1);
5503 check_added_monitors!($node, 1);
5504 let payment_event = SendEvent::from_event(events.remove(0));
5509 macro_rules! expect_payment_received {
5510 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5511 let events = $node.node.get_and_clear_pending_events();
5512 assert_eq!(events.len(), 1);
5514 Event::PaymentReceived { ref payment_hash, amt } => {
5515 assert_eq!($expected_payment_hash, *payment_hash);
5516 assert_eq!($expected_recv_value, amt);
5518 _ => panic!("Unexpected event"),
5523 let feemsat = 239; // somehow we know?
5524 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5526 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5528 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5530 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5531 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5532 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5534 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5535 _ => panic!("Unknown error variants"),
5539 let mut htlc_id = 0;
5540 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5541 // nodes[0]'s wealth
5543 let amt_msat = recv_value_0 + total_fee_msat;
5544 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5547 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5550 let (stat01_, stat11_, stat12_, stat22_) = (
5551 get_channel_value_stat!(nodes[0], chan_1.2),
5552 get_channel_value_stat!(nodes[1], chan_1.2),
5553 get_channel_value_stat!(nodes[1], chan_2.2),
5554 get_channel_value_stat!(nodes[2], chan_2.2),
5557 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5558 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5559 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5560 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5561 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5565 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5566 // attempt to get channel_reserve violation
5567 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5568 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5570 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5571 _ => panic!("Unknown error variants"),
5575 // adding pending output
5576 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5577 let amt_msat_1 = recv_value_1 + total_fee_msat;
5579 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5580 let payment_event_1 = {
5581 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5582 check_added_monitors!(nodes[0], 1);
5584 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5585 assert_eq!(events.len(), 1);
5586 SendEvent::from_event(events.remove(0))
5588 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5590 // channel reserve test with htlc pending output > 0
5591 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5593 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5594 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5595 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5596 _ => panic!("Unknown error variants"),
5601 // test channel_reserve test on nodes[1] side
5602 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5604 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5605 let secp_ctx = Secp256k1::new();
5606 let session_priv = SecretKey::from_slice(&secp_ctx, &{
5607 let mut session_key = [0; 32];
5608 rng::fill_bytes(&mut session_key);
5610 }).expect("RNG is bad!");
5612 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5613 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5614 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5615 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5616 let msg = msgs::UpdateAddHTLC {
5617 channel_id: chan_1.2,
5619 amount_msat: htlc_msat,
5620 payment_hash: our_payment_hash,
5621 cltv_expiry: htlc_cltv,
5622 onion_routing_packet: onion_packet,
5626 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5628 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5630 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5631 assert_eq!(nodes[1].node.list_channels().len(), 1);
5632 assert_eq!(nodes[1].node.list_channels().len(), 1);
5633 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5634 assert_eq!(channel_close_broadcast.len(), 1);
5635 match channel_close_broadcast[0] {
5636 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5637 assert_eq!(msg.contents.flags & 2, 2);
5639 _ => panic!("Unexpected event"),
5645 // split the rest to test holding cell
5646 let recv_value_21 = recv_value_2/2;
5647 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5649 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5650 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);
5653 // now see if they go through on both sides
5654 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5655 // but this will stuck in the holding cell
5656 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5657 check_added_monitors!(nodes[0], 0);
5658 let events = nodes[0].node.get_and_clear_pending_events();
5659 assert_eq!(events.len(), 0);
5661 // test with outbound holding cell amount > 0
5663 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5664 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5665 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5666 _ => panic!("Unknown error variants"),
5670 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5671 // this will also stuck in the holding cell
5672 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5673 check_added_monitors!(nodes[0], 0);
5674 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5675 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5677 // flush the pending htlc
5678 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5679 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5680 check_added_monitors!(nodes[1], 1);
5682 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5683 check_added_monitors!(nodes[0], 1);
5684 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5686 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5687 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5688 // No commitment_signed so get_event_msg's assert(len == 1) passes
5689 check_added_monitors!(nodes[0], 1);
5691 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5692 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5693 check_added_monitors!(nodes[1], 1);
5695 expect_pending_htlcs_forwardable!(nodes[1]);
5697 let ref payment_event_11 = expect_forward!(nodes[1]);
5698 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5699 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5701 expect_pending_htlcs_forwardable!(nodes[2]);
5702 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5704 // flush the htlcs in the holding cell
5705 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5706 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5707 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5708 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5709 expect_pending_htlcs_forwardable!(nodes[1]);
5711 let ref payment_event_3 = expect_forward!(nodes[1]);
5712 assert_eq!(payment_event_3.msgs.len(), 2);
5713 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5714 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5716 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5717 expect_pending_htlcs_forwardable!(nodes[2]);
5719 let events = nodes[2].node.get_and_clear_pending_events();
5720 assert_eq!(events.len(), 2);
5722 Event::PaymentReceived { ref payment_hash, amt } => {
5723 assert_eq!(our_payment_hash_21, *payment_hash);
5724 assert_eq!(recv_value_21, amt);
5726 _ => panic!("Unexpected event"),
5729 Event::PaymentReceived { ref payment_hash, amt } => {
5730 assert_eq!(our_payment_hash_22, *payment_hash);
5731 assert_eq!(recv_value_22, amt);
5733 _ => panic!("Unexpected event"),
5736 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5737 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5738 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5740 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);
5741 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5742 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5743 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5745 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5746 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5750 fn channel_reserve_test() {
5751 do_channel_reserve_test(false);
5752 do_channel_reserve_test(true);
5756 fn channel_monitor_network_test() {
5757 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5758 // tests that ChannelMonitor is able to recover from various states.
5759 let nodes = create_network(5);
5761 // Create some initial channels
5762 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5763 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5764 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5765 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5767 // Rebalance the network a bit by relaying one payment through all the channels...
5768 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5769 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5770 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5771 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5773 // Simple case with no pending HTLCs:
5774 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5776 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5777 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5778 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5779 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5781 get_announce_close_broadcast_events(&nodes, 0, 1);
5782 assert_eq!(nodes[0].node.list_channels().len(), 0);
5783 assert_eq!(nodes[1].node.list_channels().len(), 1);
5785 // One pending HTLC is discarded by the force-close:
5786 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5788 // Simple case of one pending HTLC to HTLC-Timeout
5789 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5791 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5792 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5793 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5794 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5796 get_announce_close_broadcast_events(&nodes, 1, 2);
5797 assert_eq!(nodes[1].node.list_channels().len(), 0);
5798 assert_eq!(nodes[2].node.list_channels().len(), 1);
5800 macro_rules! claim_funds {
5801 ($node: expr, $prev_node: expr, $preimage: expr) => {
5803 assert!($node.node.claim_funds($preimage));
5804 check_added_monitors!($node, 1);
5806 let events = $node.node.get_and_clear_pending_msg_events();
5807 assert_eq!(events.len(), 1);
5809 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5810 assert!(update_add_htlcs.is_empty());
5811 assert!(update_fail_htlcs.is_empty());
5812 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5814 _ => panic!("Unexpected event"),
5820 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5821 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5822 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5824 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5826 // Claim the payment on nodes[3], giving it knowledge of the preimage
5827 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5829 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5830 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5832 check_preimage_claim(&nodes[3], &node_txn);
5834 get_announce_close_broadcast_events(&nodes, 2, 3);
5835 assert_eq!(nodes[2].node.list_channels().len(), 0);
5836 assert_eq!(nodes[3].node.list_channels().len(), 1);
5838 { // Cheat and reset nodes[4]'s height to 1
5839 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5840 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5843 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5844 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5845 // One pending HTLC to time out:
5846 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5847 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5851 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5852 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5853 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5854 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5858 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5860 // Claim the payment on nodes[4], giving it knowledge of the preimage
5861 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5863 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5864 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5865 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5866 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5867 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5870 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5872 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5873 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5875 check_preimage_claim(&nodes[4], &node_txn);
5877 get_announce_close_broadcast_events(&nodes, 3, 4);
5878 assert_eq!(nodes[3].node.list_channels().len(), 0);
5879 assert_eq!(nodes[4].node.list_channels().len(), 0);
5883 fn test_justice_tx() {
5884 // Test justice txn built on revoked HTLC-Success tx, against both sides
5886 let nodes = create_network(2);
5887 // Create some new channels:
5888 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5890 // A pending HTLC which will be revoked:
5891 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5892 // Get the will-be-revoked local txn from nodes[0]
5893 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5894 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5895 assert_eq!(revoked_local_txn[0].input.len(), 1);
5896 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5897 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5898 assert_eq!(revoked_local_txn[1].input.len(), 1);
5899 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5900 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5901 // Revoke the old state
5902 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5905 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5906 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5908 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5909 assert_eq!(node_txn.len(), 3);
5910 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5911 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5913 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5914 node_txn.swap_remove(0);
5916 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5918 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5919 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5920 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5921 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5922 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5924 get_announce_close_broadcast_events(&nodes, 0, 1);
5926 assert_eq!(nodes[0].node.list_channels().len(), 0);
5927 assert_eq!(nodes[1].node.list_channels().len(), 0);
5929 // We test justice_tx build by A on B's revoked HTLC-Success tx
5930 // Create some new channels:
5931 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5933 // A pending HTLC which will be revoked:
5934 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5935 // Get the will-be-revoked local txn from B
5936 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5937 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5938 assert_eq!(revoked_local_txn[0].input.len(), 1);
5939 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5940 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5941 // Revoke the old state
5942 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5944 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5945 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5947 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5948 assert_eq!(node_txn.len(), 3);
5949 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5950 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5952 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5953 node_txn.swap_remove(0);
5955 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5957 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5958 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5959 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5960 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5961 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5963 get_announce_close_broadcast_events(&nodes, 0, 1);
5964 assert_eq!(nodes[0].node.list_channels().len(), 0);
5965 assert_eq!(nodes[1].node.list_channels().len(), 0);
5969 fn revoked_output_claim() {
5970 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5971 // transaction is broadcast by its counterparty
5972 let nodes = create_network(2);
5973 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5974 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5975 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5976 assert_eq!(revoked_local_txn.len(), 1);
5977 // Only output is the full channel value back to nodes[0]:
5978 assert_eq!(revoked_local_txn[0].output.len(), 1);
5979 // Send a payment through, updating everyone's latest commitment txn
5980 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5982 // Inform nodes[1] that nodes[0] broadcast a stale tx
5983 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5984 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5985 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5986 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5988 assert_eq!(node_txn[0], node_txn[2]);
5990 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5991 check_spends!(node_txn[1], chan_1.3.clone());
5993 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5994 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5995 get_announce_close_broadcast_events(&nodes, 0, 1);
5999 fn claim_htlc_outputs_shared_tx() {
6000 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6001 let nodes = create_network(2);
6003 // Create some new channel:
6004 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6006 // Rebalance the network to generate htlc in the two directions
6007 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6008 // 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
6009 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6010 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6012 // Get the will-be-revoked local txn from node[0]
6013 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6014 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6015 assert_eq!(revoked_local_txn[0].input.len(), 1);
6016 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6017 assert_eq!(revoked_local_txn[1].input.len(), 1);
6018 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6019 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6020 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6022 //Revoke the old state
6023 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6026 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6027 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6028 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6030 let events = nodes[1].node.get_and_clear_pending_events();
6031 assert_eq!(events.len(), 1);
6033 Event::PaymentFailed { payment_hash, .. } => {
6034 assert_eq!(payment_hash, payment_hash_2);
6036 _ => panic!("Unexpected event"),
6039 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6040 assert_eq!(node_txn.len(), 4);
6042 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6043 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6045 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6047 let mut witness_lens = BTreeSet::new();
6048 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6049 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6050 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6051 assert_eq!(witness_lens.len(), 3);
6052 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6053 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6054 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6056 // Next nodes[1] broadcasts its current local tx state:
6057 assert_eq!(node_txn[1].input.len(), 1);
6058 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6060 assert_eq!(node_txn[2].input.len(), 1);
6061 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6062 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6063 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6064 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6065 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6067 get_announce_close_broadcast_events(&nodes, 0, 1);
6068 assert_eq!(nodes[0].node.list_channels().len(), 0);
6069 assert_eq!(nodes[1].node.list_channels().len(), 0);
6073 fn claim_htlc_outputs_single_tx() {
6074 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6075 let nodes = create_network(2);
6077 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6079 // Rebalance the network to generate htlc in the two directions
6080 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6081 // 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
6082 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6083 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6084 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6086 // Get the will-be-revoked local txn from node[0]
6087 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6089 //Revoke the old state
6090 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6093 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6094 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6095 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6097 let events = nodes[1].node.get_and_clear_pending_events();
6098 assert_eq!(events.len(), 1);
6100 Event::PaymentFailed { payment_hash, .. } => {
6101 assert_eq!(payment_hash, payment_hash_2);
6103 _ => panic!("Unexpected event"),
6106 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6107 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)
6109 assert_eq!(node_txn[0], node_txn[7]);
6110 assert_eq!(node_txn[1], node_txn[8]);
6111 assert_eq!(node_txn[2], node_txn[9]);
6112 assert_eq!(node_txn[3], node_txn[10]);
6113 assert_eq!(node_txn[4], node_txn[11]);
6114 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6115 assert_eq!(node_txn[4], node_txn[6]);
6117 assert_eq!(node_txn[0].input.len(), 1);
6118 assert_eq!(node_txn[1].input.len(), 1);
6119 assert_eq!(node_txn[2].input.len(), 1);
6121 let mut revoked_tx_map = HashMap::new();
6122 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6123 node_txn[0].verify(&revoked_tx_map).unwrap();
6124 node_txn[1].verify(&revoked_tx_map).unwrap();
6125 node_txn[2].verify(&revoked_tx_map).unwrap();
6127 let mut witness_lens = BTreeSet::new();
6128 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6129 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6130 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6131 assert_eq!(witness_lens.len(), 3);
6132 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6133 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6134 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6136 assert_eq!(node_txn[3].input.len(), 1);
6137 check_spends!(node_txn[3], chan_1.3.clone());
6139 assert_eq!(node_txn[4].input.len(), 1);
6140 let witness_script = node_txn[4].input[0].witness.last().unwrap();
6141 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6142 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6143 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6144 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6146 get_announce_close_broadcast_events(&nodes, 0, 1);
6147 assert_eq!(nodes[0].node.list_channels().len(), 0);
6148 assert_eq!(nodes[1].node.list_channels().len(), 0);
6152 fn test_htlc_on_chain_success() {
6153 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6154 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6155 // broadcasting the right event to other nodes in payment path.
6156 // A --------------------> B ----------------------> C (preimage)
6157 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6158 // commitment transaction was broadcast.
6159 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6161 // B should be able to claim via preimage if A then broadcasts its local tx.
6162 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6163 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6164 // PaymentSent event).
6166 let nodes = create_network(3);
6168 // Create some initial channels
6169 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6170 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6172 // Rebalance the network a bit by relaying one payment through all the channels...
6173 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6174 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6176 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6177 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6179 // Broadcast legit commitment tx from C on B's chain
6180 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6181 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6182 assert_eq!(commitment_tx.len(), 1);
6183 check_spends!(commitment_tx[0], chan_2.3.clone());
6184 nodes[2].node.claim_funds(our_payment_preimage);
6185 check_added_monitors!(nodes[2], 1);
6186 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6187 assert!(updates.update_add_htlcs.is_empty());
6188 assert!(updates.update_fail_htlcs.is_empty());
6189 assert!(updates.update_fail_malformed_htlcs.is_empty());
6190 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6192 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6193 let events = nodes[2].node.get_and_clear_pending_msg_events();
6194 assert_eq!(events.len(), 1);
6196 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6197 _ => panic!("Unexpected event"),
6199 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6200 assert_eq!(node_txn.len(), 3);
6201 assert_eq!(node_txn[1], commitment_tx[0]);
6202 assert_eq!(node_txn[0], node_txn[2]);
6203 check_spends!(node_txn[0], commitment_tx[0].clone());
6204 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6205 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6206 assert_eq!(node_txn[0].lock_time, 0);
6208 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6209 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6210 let events = nodes[1].node.get_and_clear_pending_msg_events();
6212 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6213 assert_eq!(added_monitors.len(), 1);
6214 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6215 added_monitors.clear();
6217 assert_eq!(events.len(), 2);
6219 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6220 _ => panic!("Unexpected event"),
6223 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, .. } } => {
6224 assert!(update_add_htlcs.is_empty());
6225 assert!(update_fail_htlcs.is_empty());
6226 assert_eq!(update_fulfill_htlcs.len(), 1);
6227 assert!(update_fail_malformed_htlcs.is_empty());
6228 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6230 _ => panic!("Unexpected event"),
6233 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6234 // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6235 // timeout-claim of the output that nodes[2] just claimed via success.
6236 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)
6237 assert_eq!(node_txn.len(), 4);
6238 assert_eq!(node_txn[0], node_txn[3]);
6239 check_spends!(node_txn[0], commitment_tx[0].clone());
6240 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6241 assert_ne!(node_txn[0].lock_time, 0);
6242 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6243 check_spends!(node_txn[1], chan_2.3.clone());
6244 check_spends!(node_txn[2], node_txn[1].clone());
6245 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6246 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6247 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6248 assert_ne!(node_txn[2].lock_time, 0);
6252 // Broadcast legit commitment tx from A on B's chain
6253 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
6254 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6255 check_spends!(commitment_tx[0], chan_1.3.clone());
6256 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6257 let events = nodes[1].node.get_and_clear_pending_msg_events();
6258 assert_eq!(events.len(), 1);
6260 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6261 _ => panic!("Unexpected event"),
6263 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6264 assert_eq!(node_txn.len(), 3);
6265 assert_eq!(node_txn[0], node_txn[2]);
6266 check_spends!(node_txn[0], commitment_tx[0].clone());
6267 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6268 assert_eq!(node_txn[0].lock_time, 0);
6269 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6270 check_spends!(node_txn[1], chan_1.3.clone());
6271 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6272 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6273 // we already checked the same situation with A.
6275 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6276 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6277 let events = nodes[0].node.get_and_clear_pending_msg_events();
6278 assert_eq!(events.len(), 1);
6280 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6281 _ => panic!("Unexpected event"),
6283 let events = nodes[0].node.get_and_clear_pending_events();
6284 assert_eq!(events.len(), 1);
6286 Event::PaymentSent { payment_preimage } => {
6287 assert_eq!(payment_preimage, our_payment_preimage);
6289 _ => panic!("Unexpected event"),
6291 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)
6292 assert_eq!(node_txn.len(), 4);
6293 assert_eq!(node_txn[0], node_txn[3]);
6294 check_spends!(node_txn[0], commitment_tx[0].clone());
6295 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6296 assert_ne!(node_txn[0].lock_time, 0);
6297 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6298 check_spends!(node_txn[1], chan_1.3.clone());
6299 check_spends!(node_txn[2], node_txn[1].clone());
6300 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6301 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6302 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6303 assert_ne!(node_txn[2].lock_time, 0);
6307 fn test_htlc_on_chain_timeout() {
6308 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6309 // ChainWatchInterface and timeout the HTLC bacward accordingly. So here we test that ChannelManager is
6310 // broadcasting the right event to other nodes in payment path.
6311 // A ------------------> B ----------------------> C (timeout)
6312 // B's commitment tx C's commitment tx
6314 // B's HTLC timeout tx B's timeout tx
6316 let nodes = create_network(3);
6318 // Create some intial channels
6319 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6320 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6322 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6323 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6324 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6326 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6327 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6329 // Brodacast legit commitment tx from C on B's chain
6330 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6331 check_spends!(commitment_tx[0], chan_2.3.clone());
6332 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6334 let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6335 assert_eq!(added_monitors.len(), 1);
6336 added_monitors.clear();
6338 let events = nodes[2].node.get_and_clear_pending_msg_events();
6339 assert_eq!(events.len(), 1);
6341 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, .. } } => {
6342 assert!(update_add_htlcs.is_empty());
6343 assert!(!update_fail_htlcs.is_empty());
6344 assert!(update_fulfill_htlcs.is_empty());
6345 assert!(update_fail_malformed_htlcs.is_empty());
6346 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6348 _ => panic!("Unexpected event"),
6350 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6351 let events = nodes[2].node.get_and_clear_pending_msg_events();
6352 assert_eq!(events.len(), 1);
6354 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6355 _ => panic!("Unexpected event"),
6357 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6358 assert_eq!(node_txn.len(), 1);
6359 check_spends!(node_txn[0], chan_2.3.clone());
6360 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6362 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6363 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6364 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6367 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6368 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)
6369 assert_eq!(node_txn[0], node_txn[5]);
6370 assert_eq!(node_txn[1], node_txn[6]);
6371 assert_eq!(node_txn[2], node_txn[7]);
6372 check_spends!(node_txn[0], commitment_tx[0].clone());
6373 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6374 check_spends!(node_txn[1], chan_2.3.clone());
6375 check_spends!(node_txn[2], node_txn[1].clone());
6376 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6377 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6378 check_spends!(node_txn[3], chan_2.3.clone());
6379 check_spends!(node_txn[4], node_txn[3].clone());
6380 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6381 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6382 timeout_tx = node_txn[0].clone();
6386 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6387 let events = nodes[1].node.get_and_clear_pending_msg_events();
6388 check_added_monitors!(nodes[1], 1);
6389 assert_eq!(events.len(), 2);
6391 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6392 _ => panic!("Unexpected event"),
6395 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, .. } } => {
6396 assert!(update_add_htlcs.is_empty());
6397 assert!(!update_fail_htlcs.is_empty());
6398 assert!(update_fulfill_htlcs.is_empty());
6399 assert!(update_fail_malformed_htlcs.is_empty());
6400 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6402 _ => panic!("Unexpected event"),
6404 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
6405 assert_eq!(node_txn.len(), 0);
6407 // Broadcast legit commitment tx from B on A's chain
6408 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6409 check_spends!(commitment_tx[0], chan_1.3.clone());
6411 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6412 let events = nodes[0].node.get_and_clear_pending_msg_events();
6413 assert_eq!(events.len(), 1);
6415 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6416 _ => panic!("Unexpected event"),
6418 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
6419 assert_eq!(node_txn.len(), 4);
6420 assert_eq!(node_txn[0], node_txn[3]);
6421 check_spends!(node_txn[0], commitment_tx[0].clone());
6422 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6423 check_spends!(node_txn[1], chan_1.3.clone());
6424 check_spends!(node_txn[2], node_txn[1].clone());
6425 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6426 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6430 fn test_simple_commitment_revoked_fail_backward() {
6431 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6432 // and fail backward accordingly.
6434 let nodes = create_network(3);
6436 // Create some initial channels
6437 create_announced_chan_between_nodes(&nodes, 0, 1);
6438 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6440 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6441 // Get the will-be-revoked local txn from nodes[2]
6442 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6443 // Revoke the old state
6444 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6446 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6448 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6449 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6450 let events = nodes[1].node.get_and_clear_pending_msg_events();
6451 check_added_monitors!(nodes[1], 1);
6452 assert_eq!(events.len(), 2);
6454 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6455 _ => panic!("Unexpected event"),
6458 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, .. } } => {
6459 assert!(update_add_htlcs.is_empty());
6460 assert_eq!(update_fail_htlcs.len(), 1);
6461 assert!(update_fulfill_htlcs.is_empty());
6462 assert!(update_fail_malformed_htlcs.is_empty());
6463 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6465 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6466 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6468 let events = nodes[0].node.get_and_clear_pending_msg_events();
6469 assert_eq!(events.len(), 1);
6471 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6472 _ => panic!("Unexpected event"),
6474 let events = nodes[0].node.get_and_clear_pending_events();
6475 assert_eq!(events.len(), 1);
6477 Event::PaymentFailed { .. } => {},
6478 _ => panic!("Unexpected event"),
6481 _ => panic!("Unexpected event"),
6485 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6486 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6487 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6488 // commitment transaction anymore.
6489 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6490 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6491 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6492 // technically disallowed and we should probably handle it reasonably.
6493 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6494 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6496 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6497 // commitment_signed (implying it will be in the latest remote commitment transaction).
6498 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6499 // and once they revoke the previous commitment transaction (allowing us to send a new
6500 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6501 let mut nodes = create_network(3);
6503 // Create some initial channels
6504 create_announced_chan_between_nodes(&nodes, 0, 1);
6505 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6507 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6508 // Get the will-be-revoked local txn from nodes[2]
6509 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6510 // Revoke the old state
6511 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6513 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6514 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6515 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6517 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6518 check_added_monitors!(nodes[2], 1);
6519 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6520 assert!(updates.update_add_htlcs.is_empty());
6521 assert!(updates.update_fulfill_htlcs.is_empty());
6522 assert!(updates.update_fail_malformed_htlcs.is_empty());
6523 assert_eq!(updates.update_fail_htlcs.len(), 1);
6524 assert!(updates.update_fee.is_none());
6525 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6526 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6527 // Drop the last RAA from 3 -> 2
6529 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6530 check_added_monitors!(nodes[2], 1);
6531 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6532 assert!(updates.update_add_htlcs.is_empty());
6533 assert!(updates.update_fulfill_htlcs.is_empty());
6534 assert!(updates.update_fail_malformed_htlcs.is_empty());
6535 assert_eq!(updates.update_fail_htlcs.len(), 1);
6536 assert!(updates.update_fee.is_none());
6537 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6538 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6539 check_added_monitors!(nodes[1], 1);
6540 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6541 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6542 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6543 check_added_monitors!(nodes[2], 1);
6545 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6546 check_added_monitors!(nodes[2], 1);
6547 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6548 assert!(updates.update_add_htlcs.is_empty());
6549 assert!(updates.update_fulfill_htlcs.is_empty());
6550 assert!(updates.update_fail_malformed_htlcs.is_empty());
6551 assert_eq!(updates.update_fail_htlcs.len(), 1);
6552 assert!(updates.update_fee.is_none());
6553 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6554 // At this point first_payment_hash has dropped out of the latest two commitment
6555 // transactions that nodes[1] is tracking...
6556 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6557 check_added_monitors!(nodes[1], 1);
6558 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6559 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6560 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6561 check_added_monitors!(nodes[2], 1);
6563 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6564 // on nodes[2]'s RAA.
6565 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6566 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6567 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6568 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6569 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6570 check_added_monitors!(nodes[1], 0);
6573 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6574 // One monitor for the new revocation preimage, one as we generate a commitment for
6575 // nodes[0] to fail first_payment_hash backwards.
6576 check_added_monitors!(nodes[1], 2);
6579 let mut failed_htlcs = HashSet::new();
6580 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6582 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6583 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6585 let events = nodes[1].node.get_and_clear_pending_events();
6586 assert_eq!(events.len(), 1);
6588 Event::PaymentFailed { ref payment_hash, .. } => {
6589 assert_eq!(*payment_hash, fourth_payment_hash);
6591 _ => panic!("Unexpected event"),
6594 if !deliver_bs_raa {
6595 // If we delivered the RAA already then we already failed first_payment_hash backwards.
6596 check_added_monitors!(nodes[1], 1);
6599 let events = nodes[1].node.get_and_clear_pending_msg_events();
6600 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6601 match events[if deliver_bs_raa { 2 } else { 0 }] {
6602 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6603 _ => panic!("Unexpected event"),
6607 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, .. } } => {
6608 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6609 assert_eq!(update_add_htlcs.len(), 1);
6610 assert!(update_fulfill_htlcs.is_empty());
6611 assert!(update_fail_htlcs.is_empty());
6612 assert!(update_fail_malformed_htlcs.is_empty());
6614 _ => panic!("Unexpected event"),
6617 // Due to the way backwards-failing occurs we do the updates in two steps.
6618 let updates = match events[1] {
6619 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, .. } } => {
6620 assert!(update_add_htlcs.is_empty());
6621 assert_eq!(update_fail_htlcs.len(), 1);
6622 assert!(update_fulfill_htlcs.is_empty());
6623 assert!(update_fail_malformed_htlcs.is_empty());
6624 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6626 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6627 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6628 check_added_monitors!(nodes[0], 1);
6629 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6630 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6631 check_added_monitors!(nodes[1], 1);
6632 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6633 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6634 check_added_monitors!(nodes[1], 1);
6635 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6636 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6637 check_added_monitors!(nodes[0], 1);
6639 if !deliver_bs_raa {
6640 // If we delievered B's RAA we got an unknown preimage error, not something
6641 // that we should update our routing table for.
6642 let events = nodes[0].node.get_and_clear_pending_msg_events();
6643 assert_eq!(events.len(), 1);
6645 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6646 _ => panic!("Unexpected event"),
6649 let events = nodes[0].node.get_and_clear_pending_events();
6650 assert_eq!(events.len(), 1);
6652 Event::PaymentFailed { ref payment_hash, .. } => {
6653 assert!(failed_htlcs.insert(payment_hash.0));
6655 _ => panic!("Unexpected event"),
6660 _ => panic!("Unexpected event"),
6663 assert!(updates.update_add_htlcs.is_empty());
6664 assert_eq!(updates.update_fail_htlcs.len(), 2);
6665 assert!(updates.update_fulfill_htlcs.is_empty());
6666 assert!(updates.update_fail_malformed_htlcs.is_empty());
6667 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6668 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6669 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6671 let events = nodes[0].node.get_and_clear_pending_msg_events();
6672 assert_eq!(events.len(), 2);
6673 for event in events {
6675 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6676 _ => panic!("Unexpected event"),
6680 let events = nodes[0].node.get_and_clear_pending_events();
6681 assert_eq!(events.len(), 2);
6683 Event::PaymentFailed { ref payment_hash, .. } => {
6684 assert!(failed_htlcs.insert(payment_hash.0));
6686 _ => panic!("Unexpected event"),
6689 Event::PaymentFailed { ref payment_hash, .. } => {
6690 assert!(failed_htlcs.insert(payment_hash.0));
6692 _ => panic!("Unexpected event"),
6695 assert!(failed_htlcs.contains(&first_payment_hash.0));
6696 assert!(failed_htlcs.contains(&second_payment_hash.0));
6697 assert!(failed_htlcs.contains(&third_payment_hash.0));
6701 fn test_commitment_revoked_fail_backward_exhaustive() {
6702 do_test_commitment_revoked_fail_backward_exhaustive(false);
6703 do_test_commitment_revoked_fail_backward_exhaustive(true);
6707 fn test_htlc_ignore_latest_remote_commitment() {
6708 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6709 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6710 let nodes = create_network(2);
6711 create_announced_chan_between_nodes(&nodes, 0, 1);
6713 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6714 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6716 let events = nodes[0].node.get_and_clear_pending_msg_events();
6717 assert_eq!(events.len(), 1);
6719 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6720 assert_eq!(flags & 0b10, 0b10);
6722 _ => panic!("Unexpected event"),
6726 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6727 assert_eq!(node_txn.len(), 2);
6729 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6730 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6733 let events = nodes[1].node.get_and_clear_pending_msg_events();
6734 assert_eq!(events.len(), 1);
6736 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6737 assert_eq!(flags & 0b10, 0b10);
6739 _ => panic!("Unexpected event"),
6743 // Duplicate the block_connected call since this may happen due to other listeners
6744 // registering new transactions
6745 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6749 fn test_force_close_fail_back() {
6750 // Check which HTLCs are failed-backwards on channel force-closure
6751 let mut nodes = create_network(3);
6752 create_announced_chan_between_nodes(&nodes, 0, 1);
6753 create_announced_chan_between_nodes(&nodes, 1, 2);
6755 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6757 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6759 let mut payment_event = {
6760 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6761 check_added_monitors!(nodes[0], 1);
6763 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6764 assert_eq!(events.len(), 1);
6765 SendEvent::from_event(events.remove(0))
6768 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6769 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6771 let events_1 = nodes[1].node.get_and_clear_pending_events();
6772 assert_eq!(events_1.len(), 1);
6774 Event::PendingHTLCsForwardable { .. } => { },
6775 _ => panic!("Unexpected event"),
6778 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6779 nodes[1].node.process_pending_htlc_forwards();
6781 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6782 assert_eq!(events_2.len(), 1);
6783 payment_event = SendEvent::from_event(events_2.remove(0));
6784 assert_eq!(payment_event.msgs.len(), 1);
6786 check_added_monitors!(nodes[1], 1);
6787 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6788 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6789 check_added_monitors!(nodes[2], 1);
6790 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6792 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6793 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6794 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6796 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6797 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6798 assert_eq!(events_3.len(), 1);
6800 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6801 assert_eq!(flags & 0b10, 0b10);
6803 _ => panic!("Unexpected event"),
6807 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6808 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6809 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6810 // back to nodes[1] upon timeout otherwise.
6811 assert_eq!(node_txn.len(), 1);
6815 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6816 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6818 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6819 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6820 assert_eq!(events_4.len(), 1);
6822 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6823 assert_eq!(flags & 0b10, 0b10);
6825 _ => panic!("Unexpected event"),
6828 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6830 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6831 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6832 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6834 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6835 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6836 assert_eq!(node_txn.len(), 1);
6837 assert_eq!(node_txn[0].input.len(), 1);
6838 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6839 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6840 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6842 check_spends!(node_txn[0], tx);
6846 fn test_unconf_chan() {
6847 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6848 let nodes = create_network(2);
6849 create_announced_chan_between_nodes(&nodes, 0, 1);
6851 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6852 assert_eq!(channel_state.by_id.len(), 1);
6853 assert_eq!(channel_state.short_to_id.len(), 1);
6854 mem::drop(channel_state);
6856 let mut headers = Vec::new();
6857 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6858 headers.push(header.clone());
6860 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6861 headers.push(header.clone());
6863 while !headers.is_empty() {
6864 nodes[0].node.block_disconnected(&headers.pop().unwrap());
6867 let events = nodes[0].node.get_and_clear_pending_msg_events();
6868 assert_eq!(events.len(), 1);
6870 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6871 assert_eq!(flags & 0b10, 0b10);
6873 _ => panic!("Unexpected event"),
6876 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6877 assert_eq!(channel_state.by_id.len(), 0);
6878 assert_eq!(channel_state.short_to_id.len(), 0);
6881 macro_rules! get_chan_reestablish_msgs {
6882 ($src_node: expr, $dst_node: expr) => {
6884 let mut res = Vec::with_capacity(1);
6885 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6886 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6887 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6888 res.push(msg.clone());
6890 panic!("Unexpected event")
6898 macro_rules! handle_chan_reestablish_msgs {
6899 ($src_node: expr, $dst_node: expr) => {
6901 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6903 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6905 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6911 let mut revoke_and_ack = None;
6912 let mut commitment_update = None;
6913 let order = if let Some(ev) = msg_events.get(idx) {
6916 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6917 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6918 revoke_and_ack = Some(msg.clone());
6919 RAACommitmentOrder::RevokeAndACKFirst
6921 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6922 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6923 commitment_update = Some(updates.clone());
6924 RAACommitmentOrder::CommitmentFirst
6926 _ => panic!("Unexpected event"),
6929 RAACommitmentOrder::CommitmentFirst
6932 if let Some(ev) = msg_events.get(idx) {
6934 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6935 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6936 assert!(revoke_and_ack.is_none());
6937 revoke_and_ack = Some(msg.clone());
6939 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6940 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6941 assert!(commitment_update.is_none());
6942 commitment_update = Some(updates.clone());
6944 _ => panic!("Unexpected event"),
6948 (funding_locked, revoke_and_ack, commitment_update, order)
6953 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6954 /// for claims/fails they are separated out.
6955 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)) {
6956 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6957 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6958 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6959 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6961 if send_funding_locked.0 {
6962 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6964 for reestablish in reestablish_1.iter() {
6965 assert_eq!(reestablish.next_remote_commitment_number, 0);
6968 if send_funding_locked.1 {
6969 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6971 for reestablish in reestablish_2.iter() {
6972 assert_eq!(reestablish.next_remote_commitment_number, 0);
6975 if send_funding_locked.0 || send_funding_locked.1 {
6976 // If we expect any funding_locked's, both sides better have set
6977 // next_local_commitment_number to 1
6978 for reestablish in reestablish_1.iter() {
6979 assert_eq!(reestablish.next_local_commitment_number, 1);
6981 for reestablish in reestablish_2.iter() {
6982 assert_eq!(reestablish.next_local_commitment_number, 1);
6986 let mut resp_1 = Vec::new();
6987 for msg in reestablish_1 {
6988 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6989 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6991 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6992 check_added_monitors!(node_b, 1);
6994 check_added_monitors!(node_b, 0);
6997 let mut resp_2 = Vec::new();
6998 for msg in reestablish_2 {
6999 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7000 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7002 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7003 check_added_monitors!(node_a, 1);
7005 check_added_monitors!(node_a, 0);
7008 // We dont yet support both needing updates, as that would require a different commitment dance:
7009 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7010 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7012 for chan_msgs in resp_1.drain(..) {
7013 if send_funding_locked.0 {
7014 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7015 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7016 if !announcement_event.is_empty() {
7017 assert_eq!(announcement_event.len(), 1);
7018 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7019 //TODO: Test announcement_sigs re-sending
7020 } else { panic!("Unexpected event!"); }
7023 assert!(chan_msgs.0.is_none());
7026 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7027 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7028 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7029 check_added_monitors!(node_a, 1);
7031 assert!(chan_msgs.1.is_none());
7033 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7034 let commitment_update = chan_msgs.2.unwrap();
7035 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7036 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7038 assert!(commitment_update.update_add_htlcs.is_empty());
7040 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7041 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7042 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7043 for update_add in commitment_update.update_add_htlcs {
7044 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7046 for update_fulfill in commitment_update.update_fulfill_htlcs {
7047 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7049 for update_fail in commitment_update.update_fail_htlcs {
7050 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7053 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7054 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7056 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7057 check_added_monitors!(node_a, 1);
7058 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7059 // No commitment_signed so get_event_msg's assert(len == 1) passes
7060 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7061 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7062 check_added_monitors!(node_b, 1);
7065 assert!(chan_msgs.2.is_none());
7069 for chan_msgs in resp_2.drain(..) {
7070 if send_funding_locked.1 {
7071 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7072 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7073 if !announcement_event.is_empty() {
7074 assert_eq!(announcement_event.len(), 1);
7075 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7076 //TODO: Test announcement_sigs re-sending
7077 } else { panic!("Unexpected event!"); }
7080 assert!(chan_msgs.0.is_none());
7083 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7084 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7085 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7086 check_added_monitors!(node_b, 1);
7088 assert!(chan_msgs.1.is_none());
7090 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7091 let commitment_update = chan_msgs.2.unwrap();
7092 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7093 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7095 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7096 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7097 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7098 for update_add in commitment_update.update_add_htlcs {
7099 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7101 for update_fulfill in commitment_update.update_fulfill_htlcs {
7102 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7104 for update_fail in commitment_update.update_fail_htlcs {
7105 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7108 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7109 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7111 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7112 check_added_monitors!(node_b, 1);
7113 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7114 // No commitment_signed so get_event_msg's assert(len == 1) passes
7115 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7116 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7117 check_added_monitors!(node_a, 1);
7120 assert!(chan_msgs.2.is_none());
7126 fn test_simple_peer_disconnect() {
7127 // Test that we can reconnect when there are no lost messages
7128 let nodes = create_network(3);
7129 create_announced_chan_between_nodes(&nodes, 0, 1);
7130 create_announced_chan_between_nodes(&nodes, 1, 2);
7132 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7133 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7134 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7136 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7137 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7138 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7139 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7141 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7142 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7143 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7145 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7146 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7147 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7148 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7150 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7151 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7153 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7154 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7156 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7158 let events = nodes[0].node.get_and_clear_pending_events();
7159 assert_eq!(events.len(), 2);
7161 Event::PaymentSent { payment_preimage } => {
7162 assert_eq!(payment_preimage, payment_preimage_3);
7164 _ => panic!("Unexpected event"),
7167 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
7168 assert_eq!(payment_hash, payment_hash_5);
7169 assert!(rejected_by_dest);
7171 _ => panic!("Unexpected event"),
7175 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7176 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7179 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7180 // Test that we can reconnect when in-flight HTLC updates get dropped
7181 let mut nodes = create_network(2);
7182 if messages_delivered == 0 {
7183 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7184 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7186 create_announced_chan_between_nodes(&nodes, 0, 1);
7189 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();
7190 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7192 let payment_event = {
7193 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7194 check_added_monitors!(nodes[0], 1);
7196 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7197 assert_eq!(events.len(), 1);
7198 SendEvent::from_event(events.remove(0))
7200 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7202 if messages_delivered < 2 {
7203 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7205 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7206 if messages_delivered >= 3 {
7207 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7208 check_added_monitors!(nodes[1], 1);
7209 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7211 if messages_delivered >= 4 {
7212 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7213 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7214 check_added_monitors!(nodes[0], 1);
7216 if messages_delivered >= 5 {
7217 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7218 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7219 // No commitment_signed so get_event_msg's assert(len == 1) passes
7220 check_added_monitors!(nodes[0], 1);
7222 if messages_delivered >= 6 {
7223 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7224 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7225 check_added_monitors!(nodes[1], 1);
7232 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7233 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7234 if messages_delivered < 3 {
7235 // Even if the funding_locked messages get exchanged, as long as nothing further was
7236 // received on either side, both sides will need to resend them.
7237 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7238 } else if messages_delivered == 3 {
7239 // nodes[0] still wants its RAA + commitment_signed
7240 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7241 } else if messages_delivered == 4 {
7242 // nodes[0] still wants its commitment_signed
7243 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7244 } else if messages_delivered == 5 {
7245 // nodes[1] still wants its final RAA
7246 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7247 } else if messages_delivered == 6 {
7248 // Everything was delivered...
7249 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7252 let events_1 = nodes[1].node.get_and_clear_pending_events();
7253 assert_eq!(events_1.len(), 1);
7255 Event::PendingHTLCsForwardable { .. } => { },
7256 _ => panic!("Unexpected event"),
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));
7263 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7264 nodes[1].node.process_pending_htlc_forwards();
7266 let events_2 = nodes[1].node.get_and_clear_pending_events();
7267 assert_eq!(events_2.len(), 1);
7269 Event::PaymentReceived { ref payment_hash, amt } => {
7270 assert_eq!(payment_hash_1, *payment_hash);
7271 assert_eq!(amt, 1000000);
7273 _ => panic!("Unexpected event"),
7276 nodes[1].node.claim_funds(payment_preimage_1);
7277 check_added_monitors!(nodes[1], 1);
7279 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7280 assert_eq!(events_3.len(), 1);
7281 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7282 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7283 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7284 assert!(updates.update_add_htlcs.is_empty());
7285 assert!(updates.update_fail_htlcs.is_empty());
7286 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7287 assert!(updates.update_fail_malformed_htlcs.is_empty());
7288 assert!(updates.update_fee.is_none());
7289 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7291 _ => panic!("Unexpected event"),
7294 if messages_delivered >= 1 {
7295 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7297 let events_4 = nodes[0].node.get_and_clear_pending_events();
7298 assert_eq!(events_4.len(), 1);
7300 Event::PaymentSent { ref payment_preimage } => {
7301 assert_eq!(payment_preimage_1, *payment_preimage);
7303 _ => panic!("Unexpected event"),
7306 if messages_delivered >= 2 {
7307 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7308 check_added_monitors!(nodes[0], 1);
7309 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7311 if messages_delivered >= 3 {
7312 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7313 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7314 check_added_monitors!(nodes[1], 1);
7316 if messages_delivered >= 4 {
7317 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7318 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7319 // No commitment_signed so get_event_msg's assert(len == 1) passes
7320 check_added_monitors!(nodes[1], 1);
7322 if messages_delivered >= 5 {
7323 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7324 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7325 check_added_monitors!(nodes[0], 1);
7332 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7333 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7334 if messages_delivered < 2 {
7335 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7336 //TODO: Deduplicate PaymentSent events, then enable this if:
7337 //if messages_delivered < 1 {
7338 let events_4 = nodes[0].node.get_and_clear_pending_events();
7339 assert_eq!(events_4.len(), 1);
7341 Event::PaymentSent { ref payment_preimage } => {
7342 assert_eq!(payment_preimage_1, *payment_preimage);
7344 _ => panic!("Unexpected event"),
7347 } else if messages_delivered == 2 {
7348 // nodes[0] still wants its RAA + commitment_signed
7349 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7350 } else if messages_delivered == 3 {
7351 // nodes[0] still wants its commitment_signed
7352 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7353 } else if messages_delivered == 4 {
7354 // nodes[1] still wants its final RAA
7355 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7356 } else if messages_delivered == 5 {
7357 // Everything was delivered...
7358 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7361 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7362 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7363 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7365 // Channel should still work fine...
7366 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7367 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7371 fn test_drop_messages_peer_disconnect_a() {
7372 do_test_drop_messages_peer_disconnect(0);
7373 do_test_drop_messages_peer_disconnect(1);
7374 do_test_drop_messages_peer_disconnect(2);
7375 do_test_drop_messages_peer_disconnect(3);
7379 fn test_drop_messages_peer_disconnect_b() {
7380 do_test_drop_messages_peer_disconnect(4);
7381 do_test_drop_messages_peer_disconnect(5);
7382 do_test_drop_messages_peer_disconnect(6);
7386 fn test_funding_peer_disconnect() {
7387 // Test that we can lock in our funding tx while disconnected
7388 let nodes = create_network(2);
7389 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7391 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7392 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7394 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7395 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7396 assert_eq!(events_1.len(), 1);
7398 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7399 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7401 _ => panic!("Unexpected event"),
7404 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7406 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7407 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7409 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7410 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7411 assert_eq!(events_2.len(), 2);
7413 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7414 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7416 _ => panic!("Unexpected event"),
7419 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7420 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7422 _ => panic!("Unexpected event"),
7425 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7427 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7428 // rebroadcasting announcement_signatures upon reconnect.
7430 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();
7431 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7432 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7436 fn test_drop_messages_peer_disconnect_dual_htlc() {
7437 // Test that we can handle reconnecting when both sides of a channel have pending
7438 // commitment_updates when we disconnect.
7439 let mut nodes = create_network(2);
7440 create_announced_chan_between_nodes(&nodes, 0, 1);
7442 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7444 // Now try to send a second payment which will fail to send
7445 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7446 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7448 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7449 check_added_monitors!(nodes[0], 1);
7451 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7452 assert_eq!(events_1.len(), 1);
7454 MessageSendEvent::UpdateHTLCs { .. } => {},
7455 _ => panic!("Unexpected event"),
7458 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7459 check_added_monitors!(nodes[1], 1);
7461 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7462 assert_eq!(events_2.len(), 1);
7464 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 } } => {
7465 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7466 assert!(update_add_htlcs.is_empty());
7467 assert_eq!(update_fulfill_htlcs.len(), 1);
7468 assert!(update_fail_htlcs.is_empty());
7469 assert!(update_fail_malformed_htlcs.is_empty());
7470 assert!(update_fee.is_none());
7472 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7473 let events_3 = nodes[0].node.get_and_clear_pending_events();
7474 assert_eq!(events_3.len(), 1);
7476 Event::PaymentSent { ref payment_preimage } => {
7477 assert_eq!(*payment_preimage, payment_preimage_1);
7479 _ => panic!("Unexpected event"),
7482 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7483 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7484 // No commitment_signed so get_event_msg's assert(len == 1) passes
7485 check_added_monitors!(nodes[0], 1);
7487 _ => panic!("Unexpected event"),
7490 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7491 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7493 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7494 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7495 assert_eq!(reestablish_1.len(), 1);
7496 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7497 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7498 assert_eq!(reestablish_2.len(), 1);
7500 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7501 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7502 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7503 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7505 assert!(as_resp.0.is_none());
7506 assert!(bs_resp.0.is_none());
7508 assert!(bs_resp.1.is_none());
7509 assert!(bs_resp.2.is_none());
7511 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7513 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7514 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7515 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7516 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7517 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7518 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();
7519 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7520 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7521 // No commitment_signed so get_event_msg's assert(len == 1) passes
7522 check_added_monitors!(nodes[1], 1);
7524 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7525 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7526 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7527 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7528 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7529 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7530 assert!(bs_second_commitment_signed.update_fee.is_none());
7531 check_added_monitors!(nodes[1], 1);
7533 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7534 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7535 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7536 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7537 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7538 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7539 assert!(as_commitment_signed.update_fee.is_none());
7540 check_added_monitors!(nodes[0], 1);
7542 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7543 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7544 // No commitment_signed so get_event_msg's assert(len == 1) passes
7545 check_added_monitors!(nodes[0], 1);
7547 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7548 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7549 // No commitment_signed so get_event_msg's assert(len == 1) passes
7550 check_added_monitors!(nodes[1], 1);
7552 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7553 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7554 check_added_monitors!(nodes[1], 1);
7556 let events_4 = nodes[1].node.get_and_clear_pending_events();
7557 assert_eq!(events_4.len(), 1);
7559 Event::PendingHTLCsForwardable { .. } => { },
7560 _ => panic!("Unexpected event"),
7563 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7564 nodes[1].node.process_pending_htlc_forwards();
7566 let events_5 = nodes[1].node.get_and_clear_pending_events();
7567 assert_eq!(events_5.len(), 1);
7569 Event::PaymentReceived { ref payment_hash, amt: _ } => {
7570 assert_eq!(payment_hash_2, *payment_hash);
7572 _ => panic!("Unexpected event"),
7575 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7576 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7577 check_added_monitors!(nodes[0], 1);
7579 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7583 fn test_simple_monitor_permanent_update_fail() {
7584 // Test that we handle a simple permanent monitor update failure
7585 let mut nodes = create_network(2);
7586 create_announced_chan_between_nodes(&nodes, 0, 1);
7588 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7589 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7591 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7592 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7593 check_added_monitors!(nodes[0], 1);
7595 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7596 assert_eq!(events_1.len(), 2);
7598 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7599 _ => panic!("Unexpected event"),
7602 MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7603 _ => panic!("Unexpected event"),
7606 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7607 // PaymentFailed event
7609 assert_eq!(nodes[0].node.list_channels().len(), 0);
7612 fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7613 // Test that we can recover from a simple temporary monitor update failure optionally with
7614 // a disconnect in between
7615 let mut nodes = create_network(2);
7616 create_announced_chan_between_nodes(&nodes, 0, 1);
7618 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7619 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7621 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7622 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7623 check_added_monitors!(nodes[0], 1);
7625 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7626 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7627 assert_eq!(nodes[0].node.list_channels().len(), 1);
7630 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7631 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7632 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7635 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7636 nodes[0].node.test_restore_channel_monitor();
7637 check_added_monitors!(nodes[0], 1);
7639 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7640 assert_eq!(events_2.len(), 1);
7641 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7642 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7643 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7644 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7646 expect_pending_htlcs_forwardable!(nodes[1]);
7648 let events_3 = nodes[1].node.get_and_clear_pending_events();
7649 assert_eq!(events_3.len(), 1);
7651 Event::PaymentReceived { ref payment_hash, amt } => {
7652 assert_eq!(payment_hash_1, *payment_hash);
7653 assert_eq!(amt, 1000000);
7655 _ => panic!("Unexpected event"),
7658 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7660 // Now set it to failed again...
7661 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7662 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7663 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7664 check_added_monitors!(nodes[0], 1);
7666 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7667 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7668 assert_eq!(nodes[0].node.list_channels().len(), 1);
7671 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7672 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7673 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7676 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7677 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7678 nodes[0].node.test_restore_channel_monitor();
7679 check_added_monitors!(nodes[0], 1);
7681 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7682 assert_eq!(events_5.len(), 1);
7684 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7685 _ => panic!("Unexpected event"),
7688 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7689 // PaymentFailed event
7691 assert_eq!(nodes[0].node.list_channels().len(), 0);
7695 fn test_simple_monitor_temporary_update_fail() {
7696 do_test_simple_monitor_temporary_update_fail(false);
7697 do_test_simple_monitor_temporary_update_fail(true);
7700 fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7701 let disconnect_flags = 8 | 16;
7703 // Test that we can recover from a temporary monitor update failure with some in-flight
7704 // HTLCs going on at the same time potentially with some disconnection thrown in.
7705 // * First we route a payment, then get a temporary monitor update failure when trying to
7706 // route a second payment. We then claim the first payment.
7707 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7708 // TemporaryFailure likely indicates net disconnect which resulted in failing to update
7709 // the ChannelMonitor on a watchtower).
7710 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7711 // immediately, otherwise we wait sconnect and deliver them via the reconnect
7712 // channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7713 // disconnect_count & !disconnect_flags is 0).
7714 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7715 // through message sending, potentially disconnect/reconnecting multiple times based on
7716 // disconnect_count, to get the update_fulfill_htlc through.
7717 // * We then walk through more message exchanges to get the original update_add_htlc
7718 // through, swapping message ordering based on disconnect_count & 8 and optionally
7719 // disconnect/reconnecting based on disconnect_count.
7720 let mut nodes = create_network(2);
7721 create_announced_chan_between_nodes(&nodes, 0, 1);
7723 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7725 // Now try to send a second payment which will fail to send
7726 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7727 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7729 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7730 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7731 check_added_monitors!(nodes[0], 1);
7733 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7734 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7735 assert_eq!(nodes[0].node.list_channels().len(), 1);
7737 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7738 // but nodes[0] won't respond since it is frozen.
7739 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7740 check_added_monitors!(nodes[1], 1);
7741 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7742 assert_eq!(events_2.len(), 1);
7743 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7744 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 } } => {
7745 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7746 assert!(update_add_htlcs.is_empty());
7747 assert_eq!(update_fulfill_htlcs.len(), 1);
7748 assert!(update_fail_htlcs.is_empty());
7749 assert!(update_fail_malformed_htlcs.is_empty());
7750 assert!(update_fee.is_none());
7752 if (disconnect_count & 16) == 0 {
7753 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7754 let events_3 = nodes[0].node.get_and_clear_pending_events();
7755 assert_eq!(events_3.len(), 1);
7757 Event::PaymentSent { ref payment_preimage } => {
7758 assert_eq!(*payment_preimage, payment_preimage_1);
7760 _ => panic!("Unexpected event"),
7763 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) {
7764 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7765 } else { panic!(); }
7768 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7770 _ => panic!("Unexpected event"),
7773 if disconnect_count & !disconnect_flags > 0 {
7774 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7775 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7778 // Now fix monitor updating...
7779 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7780 nodes[0].node.test_restore_channel_monitor();
7781 check_added_monitors!(nodes[0], 1);
7783 macro_rules! disconnect_reconnect_peers { () => { {
7784 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7785 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7787 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7788 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7789 assert_eq!(reestablish_1.len(), 1);
7790 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7791 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7792 assert_eq!(reestablish_2.len(), 1);
7794 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7795 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7796 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7797 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7799 assert!(as_resp.0.is_none());
7800 assert!(bs_resp.0.is_none());
7802 (reestablish_1, reestablish_2, as_resp, bs_resp)
7805 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7806 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7809 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7810 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7811 assert_eq!(reestablish_1.len(), 1);
7812 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7813 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7814 assert_eq!(reestablish_2.len(), 1);
7816 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7817 check_added_monitors!(nodes[0], 0);
7818 let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7819 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7820 check_added_monitors!(nodes[1], 0);
7821 let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7823 assert!(as_resp.0.is_none());
7824 assert!(bs_resp.0.is_none());
7826 assert!(bs_resp.1.is_none());
7827 if (disconnect_count & 16) == 0 {
7828 assert!(bs_resp.2.is_none());
7830 assert!(as_resp.1.is_some());
7831 assert!(as_resp.2.is_some());
7832 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7834 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7835 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7836 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7837 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7838 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7839 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7841 assert!(as_resp.1.is_none());
7843 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();
7844 let events_3 = nodes[0].node.get_and_clear_pending_events();
7845 assert_eq!(events_3.len(), 1);
7847 Event::PaymentSent { ref payment_preimage } => {
7848 assert_eq!(*payment_preimage, payment_preimage_1);
7850 _ => panic!("Unexpected event"),
7853 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7854 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7855 // No commitment_signed so get_event_msg's assert(len == 1) passes
7856 check_added_monitors!(nodes[0], 1);
7858 as_resp.1 = Some(as_resp_raa);
7862 if disconnect_count & !disconnect_flags > 1 {
7863 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7865 if (disconnect_count & 16) == 0 {
7866 assert!(reestablish_1 == second_reestablish_1);
7867 assert!(reestablish_2 == second_reestablish_2);
7869 assert!(as_resp == second_as_resp);
7870 assert!(bs_resp == second_bs_resp);
7873 (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7875 let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7876 assert_eq!(events_4.len(), 2);
7877 (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7878 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7879 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7882 _ => panic!("Unexpected event"),
7886 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7888 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7890 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7891 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7892 check_added_monitors!(nodes[1], 1);
7894 if disconnect_count & !disconnect_flags > 2 {
7895 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7897 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7898 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7900 assert!(as_resp.2.is_none());
7901 assert!(bs_resp.2.is_none());
7904 let as_commitment_update;
7905 let bs_second_commitment_update;
7907 macro_rules! handle_bs_raa { () => {
7908 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7909 as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7910 assert!(as_commitment_update.update_add_htlcs.is_empty());
7911 assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7912 assert!(as_commitment_update.update_fail_htlcs.is_empty());
7913 assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7914 assert!(as_commitment_update.update_fee.is_none());
7915 check_added_monitors!(nodes[0], 1);
7918 macro_rules! handle_initial_raa { () => {
7919 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7920 bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7921 assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7922 assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7923 assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7924 assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7925 assert!(bs_second_commitment_update.update_fee.is_none());
7926 check_added_monitors!(nodes[1], 1);
7929 if (disconnect_count & 8) == 0 {
7932 if disconnect_count & !disconnect_flags > 3 {
7933 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7935 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7936 assert!(bs_resp.1.is_none());
7938 assert!(as_resp.2.unwrap() == as_commitment_update);
7939 assert!(bs_resp.2.is_none());
7941 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7944 handle_initial_raa!();
7946 if disconnect_count & !disconnect_flags > 4 {
7947 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7949 assert!(as_resp.1.is_none());
7950 assert!(bs_resp.1.is_none());
7952 assert!(as_resp.2.unwrap() == as_commitment_update);
7953 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7956 handle_initial_raa!();
7958 if disconnect_count & !disconnect_flags > 3 {
7959 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7961 assert!(as_resp.1.is_none());
7962 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7964 assert!(as_resp.2.is_none());
7965 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7967 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7972 if disconnect_count & !disconnect_flags > 4 {
7973 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7975 assert!(as_resp.1.is_none());
7976 assert!(bs_resp.1.is_none());
7978 assert!(as_resp.2.unwrap() == as_commitment_update);
7979 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7983 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7984 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7985 // No commitment_signed so get_event_msg's assert(len == 1) passes
7986 check_added_monitors!(nodes[0], 1);
7988 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7989 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7990 // No commitment_signed so get_event_msg's assert(len == 1) passes
7991 check_added_monitors!(nodes[1], 1);
7993 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7994 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7995 check_added_monitors!(nodes[1], 1);
7997 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7998 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7999 check_added_monitors!(nodes[0], 1);
8001 expect_pending_htlcs_forwardable!(nodes[1]);
8003 let events_5 = nodes[1].node.get_and_clear_pending_events();
8004 assert_eq!(events_5.len(), 1);
8006 Event::PaymentReceived { ref payment_hash, amt } => {
8007 assert_eq!(payment_hash_2, *payment_hash);
8008 assert_eq!(amt, 1000000);
8010 _ => panic!("Unexpected event"),
8013 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8017 fn test_monitor_temporary_update_fail_a() {
8018 do_test_monitor_temporary_update_fail(0);
8019 do_test_monitor_temporary_update_fail(1);
8020 do_test_monitor_temporary_update_fail(2);
8021 do_test_monitor_temporary_update_fail(3);
8022 do_test_monitor_temporary_update_fail(4);
8023 do_test_monitor_temporary_update_fail(5);
8027 fn test_monitor_temporary_update_fail_b() {
8028 do_test_monitor_temporary_update_fail(2 | 8);
8029 do_test_monitor_temporary_update_fail(3 | 8);
8030 do_test_monitor_temporary_update_fail(4 | 8);
8031 do_test_monitor_temporary_update_fail(5 | 8);
8035 fn test_monitor_temporary_update_fail_c() {
8036 do_test_monitor_temporary_update_fail(1 | 16);
8037 do_test_monitor_temporary_update_fail(2 | 16);
8038 do_test_monitor_temporary_update_fail(3 | 16);
8039 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8040 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8044 fn test_monitor_update_fail_cs() {
8045 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8046 let mut nodes = create_network(2);
8047 create_announced_chan_between_nodes(&nodes, 0, 1);
8049 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8050 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8051 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8052 check_added_monitors!(nodes[0], 1);
8054 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8055 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8057 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8058 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() {
8059 assert_eq!(err, "Failed to update ChannelMonitor");
8060 } else { panic!(); }
8061 check_added_monitors!(nodes[1], 1);
8062 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8064 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8065 nodes[1].node.test_restore_channel_monitor();
8066 check_added_monitors!(nodes[1], 1);
8067 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8068 assert_eq!(responses.len(), 2);
8070 match responses[0] {
8071 MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8072 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8073 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8074 check_added_monitors!(nodes[0], 1);
8076 _ => panic!("Unexpected event"),
8078 match responses[1] {
8079 MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8080 assert!(updates.update_add_htlcs.is_empty());
8081 assert!(updates.update_fulfill_htlcs.is_empty());
8082 assert!(updates.update_fail_htlcs.is_empty());
8083 assert!(updates.update_fail_malformed_htlcs.is_empty());
8084 assert!(updates.update_fee.is_none());
8085 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8087 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8088 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() {
8089 assert_eq!(err, "Failed to update ChannelMonitor");
8090 } else { panic!(); }
8091 check_added_monitors!(nodes[0], 1);
8092 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8094 _ => panic!("Unexpected event"),
8097 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8098 nodes[0].node.test_restore_channel_monitor();
8099 check_added_monitors!(nodes[0], 1);
8101 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8102 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8103 check_added_monitors!(nodes[1], 1);
8105 let mut events = nodes[1].node.get_and_clear_pending_events();
8106 assert_eq!(events.len(), 1);
8108 Event::PendingHTLCsForwardable { .. } => { },
8109 _ => panic!("Unexpected event"),
8111 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8112 nodes[1].node.process_pending_htlc_forwards();
8114 events = nodes[1].node.get_and_clear_pending_events();
8115 assert_eq!(events.len(), 1);
8117 Event::PaymentReceived { payment_hash, amt } => {
8118 assert_eq!(payment_hash, our_payment_hash);
8119 assert_eq!(amt, 1000000);
8121 _ => panic!("Unexpected event"),
8124 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8127 fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8128 // Tests handling of a monitor update failure when processing an incoming RAA
8129 let mut nodes = create_network(3);
8130 create_announced_chan_between_nodes(&nodes, 0, 1);
8131 create_announced_chan_between_nodes(&nodes, 1, 2);
8133 // Rebalance a bit so that we can send backwards from 2 to 1.
8134 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8136 // Route a first payment that we'll fail backwards
8137 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8139 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8140 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8141 check_added_monitors!(nodes[2], 1);
8143 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8144 assert!(updates.update_add_htlcs.is_empty());
8145 assert!(updates.update_fulfill_htlcs.is_empty());
8146 assert_eq!(updates.update_fail_htlcs.len(), 1);
8147 assert!(updates.update_fail_malformed_htlcs.is_empty());
8148 assert!(updates.update_fee.is_none());
8149 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8151 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8152 check_added_monitors!(nodes[0], 0);
8154 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8156 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8157 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8158 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8159 check_added_monitors!(nodes[0], 1);
8161 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8162 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8163 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8165 let events_1 = nodes[1].node.get_and_clear_pending_events();
8166 assert_eq!(events_1.len(), 1);
8168 Event::PendingHTLCsForwardable { .. } => { },
8169 _ => panic!("Unexpected event"),
8172 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8173 nodes[1].node.process_pending_htlc_forwards();
8174 check_added_monitors!(nodes[1], 0);
8175 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8177 // Now fail monitor updating.
8178 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8179 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() {
8180 assert_eq!(err, "Failed to update ChannelMonitor");
8181 } else { panic!(); }
8182 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8183 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8184 check_added_monitors!(nodes[1], 1);
8186 // Attempt to forward a third payment but fail due to the second channel being unavailable
8189 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8190 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8191 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8192 check_added_monitors!(nodes[0], 1);
8194 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8195 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8196 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8197 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8198 check_added_monitors!(nodes[1], 0);
8200 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8201 assert_eq!(events_2.len(), 1);
8202 match events_2.remove(0) {
8203 MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8204 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8205 assert!(updates.update_fulfill_htlcs.is_empty());
8206 assert_eq!(updates.update_fail_htlcs.len(), 1);
8207 assert!(updates.update_fail_malformed_htlcs.is_empty());
8208 assert!(updates.update_add_htlcs.is_empty());
8209 assert!(updates.update_fee.is_none());
8211 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8212 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8214 let events = nodes[0].node.get_and_clear_pending_events();
8215 assert_eq!(events.len(), 1);
8216 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events[0] {
8217 assert_eq!(payment_hash, payment_hash_3);
8218 assert!(!rejected_by_dest);
8219 } else { panic!("Unexpected event!"); }
8221 _ => panic!("Unexpected event type!"),
8224 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8225 // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8226 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8227 let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8228 nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8229 check_added_monitors!(nodes[2], 1);
8231 send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8232 nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8233 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) {
8234 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8235 } else { panic!(); }
8236 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8237 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8238 (Some(payment_preimage_4), Some(payment_hash_4))
8239 } else { (None, None) };
8241 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8242 // update_add update.
8243 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8244 nodes[1].node.test_restore_channel_monitor();
8245 check_added_monitors!(nodes[1], 2);
8247 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8248 if test_ignore_second_cs {
8249 assert_eq!(events_3.len(), 3);
8251 assert_eq!(events_3.len(), 2);
8254 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8255 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8256 let messages_a = match events_3.pop().unwrap() {
8257 MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8258 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8259 assert!(updates.update_fulfill_htlcs.is_empty());
8260 assert_eq!(updates.update_fail_htlcs.len(), 1);
8261 assert!(updates.update_fail_malformed_htlcs.is_empty());
8262 assert!(updates.update_add_htlcs.is_empty());
8263 assert!(updates.update_fee.is_none());
8264 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8266 _ => panic!("Unexpected event type!"),
8268 let raa = if test_ignore_second_cs {
8269 match events_3.remove(1) {
8270 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8271 assert_eq!(node_id, nodes[2].node.get_our_node_id());
8274 _ => panic!("Unexpected event"),
8277 let send_event_b = SendEvent::from_event(events_3.remove(0));
8278 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8280 // Now deliver the new messages...
8282 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8283 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8284 let events_4 = nodes[0].node.get_and_clear_pending_events();
8285 assert_eq!(events_4.len(), 1);
8286 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events_4[0] {
8287 assert_eq!(payment_hash, payment_hash_1);
8288 assert!(rejected_by_dest);
8289 } else { panic!("Unexpected event!"); }
8291 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8292 if test_ignore_second_cs {
8293 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8294 check_added_monitors!(nodes[2], 1);
8295 let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8296 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8297 check_added_monitors!(nodes[2], 1);
8298 let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8299 assert!(bs_cs.update_add_htlcs.is_empty());
8300 assert!(bs_cs.update_fail_htlcs.is_empty());
8301 assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8302 assert!(bs_cs.update_fulfill_htlcs.is_empty());
8303 assert!(bs_cs.update_fee.is_none());
8305 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8306 check_added_monitors!(nodes[1], 1);
8307 let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8308 assert!(as_cs.update_add_htlcs.is_empty());
8309 assert!(as_cs.update_fail_htlcs.is_empty());
8310 assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8311 assert!(as_cs.update_fulfill_htlcs.is_empty());
8312 assert!(as_cs.update_fee.is_none());
8314 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8315 check_added_monitors!(nodes[1], 1);
8316 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8318 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8319 check_added_monitors!(nodes[2], 1);
8320 let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8322 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8323 check_added_monitors!(nodes[2], 1);
8324 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8326 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8327 check_added_monitors!(nodes[1], 1);
8328 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8330 commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8333 let events_5 = nodes[2].node.get_and_clear_pending_events();
8334 assert_eq!(events_5.len(), 1);
8336 Event::PendingHTLCsForwardable { .. } => { },
8337 _ => panic!("Unexpected event"),
8340 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8341 nodes[2].node.process_pending_htlc_forwards();
8343 let events_6 = nodes[2].node.get_and_clear_pending_events();
8344 assert_eq!(events_6.len(), 1);
8346 Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8347 _ => panic!("Unexpected event"),
8350 if test_ignore_second_cs {
8351 let events_7 = nodes[1].node.get_and_clear_pending_events();
8352 assert_eq!(events_7.len(), 1);
8354 Event::PendingHTLCsForwardable { .. } => { },
8355 _ => panic!("Unexpected event"),
8358 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8359 nodes[1].node.process_pending_htlc_forwards();
8360 check_added_monitors!(nodes[1], 1);
8362 send_event = SendEvent::from_node(&nodes[1]);
8363 assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8364 assert_eq!(send_event.msgs.len(), 1);
8365 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8366 commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8368 let events_8 = nodes[0].node.get_and_clear_pending_events();
8369 assert_eq!(events_8.len(), 1);
8371 Event::PendingHTLCsForwardable { .. } => { },
8372 _ => panic!("Unexpected event"),
8375 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8376 nodes[0].node.process_pending_htlc_forwards();
8378 let events_9 = nodes[0].node.get_and_clear_pending_events();
8379 assert_eq!(events_9.len(), 1);
8381 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8382 _ => panic!("Unexpected event"),
8384 claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8387 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8391 fn test_monitor_update_fail_raa() {
8392 do_test_monitor_update_fail_raa(false);
8393 do_test_monitor_update_fail_raa(true);
8397 fn test_monitor_update_fail_reestablish() {
8398 // Simple test for message retransmission after monitor update failure on
8399 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8401 let mut nodes = create_network(3);
8402 create_announced_chan_between_nodes(&nodes, 0, 1);
8403 create_announced_chan_between_nodes(&nodes, 1, 2);
8405 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8407 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8408 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8410 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8411 check_added_monitors!(nodes[2], 1);
8412 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8413 assert!(updates.update_add_htlcs.is_empty());
8414 assert!(updates.update_fail_htlcs.is_empty());
8415 assert!(updates.update_fail_malformed_htlcs.is_empty());
8416 assert!(updates.update_fee.is_none());
8417 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8418 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8419 check_added_monitors!(nodes[1], 1);
8420 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8421 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8423 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8424 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8425 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8427 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8428 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8430 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8432 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() {
8433 assert_eq!(err, "Failed to update ChannelMonitor");
8434 } else { panic!(); }
8435 check_added_monitors!(nodes[1], 1);
8437 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8438 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8440 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8441 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8443 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8444 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8446 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8448 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8449 check_added_monitors!(nodes[1], 0);
8450 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8452 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8453 nodes[1].node.test_restore_channel_monitor();
8454 check_added_monitors!(nodes[1], 1);
8456 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8457 assert!(updates.update_add_htlcs.is_empty());
8458 assert!(updates.update_fail_htlcs.is_empty());
8459 assert!(updates.update_fail_malformed_htlcs.is_empty());
8460 assert!(updates.update_fee.is_none());
8461 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8462 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8463 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8465 let events = nodes[0].node.get_and_clear_pending_events();
8466 assert_eq!(events.len(), 1);
8468 Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8469 _ => panic!("Unexpected event"),
8474 fn test_invalid_channel_announcement() {
8475 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8476 let secp_ctx = Secp256k1::new();
8477 let nodes = create_network(2);
8479 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8481 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8482 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8483 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8484 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8486 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 } );
8488 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8489 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8491 let as_network_key = nodes[0].node.get_our_node_id();
8492 let bs_network_key = nodes[1].node.get_our_node_id();
8494 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8496 let mut chan_announcement;
8498 macro_rules! dummy_unsigned_msg {
8500 msgs::UnsignedChannelAnnouncement {
8501 features: msgs::GlobalFeatures::new(),
8502 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8503 short_channel_id: as_chan.get_short_channel_id().unwrap(),
8504 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8505 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8506 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8507 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8508 excess_data: Vec::new(),
8513 macro_rules! sign_msg {
8514 ($unsigned_msg: expr) => {
8515 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8516 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8517 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8518 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8519 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8520 chan_announcement = msgs::ChannelAnnouncement {
8521 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8522 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8523 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8524 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8525 contents: $unsigned_msg
8530 let unsigned_msg = dummy_unsigned_msg!();
8531 sign_msg!(unsigned_msg);
8532 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8533 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 } );
8535 // Configured with Network::Testnet
8536 let mut unsigned_msg = dummy_unsigned_msg!();
8537 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8538 sign_msg!(unsigned_msg);
8539 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8541 let mut unsigned_msg = dummy_unsigned_msg!();
8542 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8543 sign_msg!(unsigned_msg);
8544 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8547 struct VecWriter(Vec<u8>);
8548 impl Writer for VecWriter {
8549 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8550 self.0.extend_from_slice(buf);
8553 fn size_hint(&mut self, size: usize) {
8554 self.0.reserve_exact(size);
8559 fn test_no_txn_manager_serialize_deserialize() {
8560 let mut nodes = create_network(2);
8562 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8564 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8566 let nodes_0_serialized = nodes[0].node.encode();
8567 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8568 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8570 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())));
8571 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8572 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8573 assert!(chan_0_monitor_read.is_empty());
8575 let mut nodes_0_read = &nodes_0_serialized[..];
8576 let config = UserConfig::new();
8577 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8578 let (_, nodes_0_deserialized) = {
8579 let mut channel_monitors = HashMap::new();
8580 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8581 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8582 default_config: config,
8584 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8585 monitor: nodes[0].chan_monitor.clone(),
8586 chain_monitor: nodes[0].chain_monitor.clone(),
8587 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8588 logger: Arc::new(test_utils::TestLogger::new()),
8589 channel_monitors: &channel_monitors,
8592 assert!(nodes_0_read.is_empty());
8594 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8595 nodes[0].node = Arc::new(nodes_0_deserialized);
8596 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8597 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8598 assert_eq!(nodes[0].node.list_channels().len(), 1);
8599 check_added_monitors!(nodes[0], 1);
8601 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8602 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8603 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8604 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8606 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8607 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8608 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8609 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8611 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8612 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8613 for node in nodes.iter() {
8614 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8615 node.router.handle_channel_update(&as_update).unwrap();
8616 node.router.handle_channel_update(&bs_update).unwrap();
8619 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8623 fn test_simple_manager_serialize_deserialize() {
8624 let mut nodes = create_network(2);
8625 create_announced_chan_between_nodes(&nodes, 0, 1);
8627 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8628 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8630 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8632 let nodes_0_serialized = nodes[0].node.encode();
8633 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8634 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8636 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())));
8637 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8638 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8639 assert!(chan_0_monitor_read.is_empty());
8641 let mut nodes_0_read = &nodes_0_serialized[..];
8642 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8643 let (_, nodes_0_deserialized) = {
8644 let mut channel_monitors = HashMap::new();
8645 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8646 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8647 default_config: UserConfig::new(),
8649 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8650 monitor: nodes[0].chan_monitor.clone(),
8651 chain_monitor: nodes[0].chain_monitor.clone(),
8652 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8653 logger: Arc::new(test_utils::TestLogger::new()),
8654 channel_monitors: &channel_monitors,
8657 assert!(nodes_0_read.is_empty());
8659 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8660 nodes[0].node = Arc::new(nodes_0_deserialized);
8661 check_added_monitors!(nodes[0], 1);
8663 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8665 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8666 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8670 fn test_manager_serialize_deserialize_inconsistent_monitor() {
8671 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8672 let mut nodes = create_network(4);
8673 create_announced_chan_between_nodes(&nodes, 0, 1);
8674 create_announced_chan_between_nodes(&nodes, 2, 0);
8675 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8677 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8679 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8680 let nodes_0_serialized = nodes[0].node.encode();
8682 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8683 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8684 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8685 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8687 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8689 let mut node_0_monitors_serialized = Vec::new();
8690 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8691 let mut writer = VecWriter(Vec::new());
8692 monitor.1.write_for_disk(&mut writer).unwrap();
8693 node_0_monitors_serialized.push(writer.0);
8696 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())));
8697 let mut node_0_monitors = Vec::new();
8698 for serialized in node_0_monitors_serialized.iter() {
8699 let mut read = &serialized[..];
8700 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8701 assert!(read.is_empty());
8702 node_0_monitors.push(monitor);
8705 let mut nodes_0_read = &nodes_0_serialized[..];
8706 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8707 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8708 default_config: UserConfig::new(),
8710 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8711 monitor: nodes[0].chan_monitor.clone(),
8712 chain_monitor: nodes[0].chain_monitor.clone(),
8713 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8714 logger: Arc::new(test_utils::TestLogger::new()),
8715 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8717 assert!(nodes_0_read.is_empty());
8719 { // Channel close should result in a commitment tx and an HTLC tx
8720 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8721 assert_eq!(txn.len(), 2);
8722 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8723 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8726 for monitor in node_0_monitors.drain(..) {
8727 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8728 check_added_monitors!(nodes[0], 1);
8730 nodes[0].node = Arc::new(nodes_0_deserialized);
8732 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8733 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8734 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8735 //... and we can even still claim the payment!
8736 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8738 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8739 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8740 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8741 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) {
8742 assert_eq!(msg.channel_id, channel_id);
8743 } else { panic!("Unexpected result"); }
8746 macro_rules! check_spendable_outputs {
8747 ($node: expr, $der_idx: expr) => {
8749 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8750 let mut txn = Vec::new();
8751 for event in events {
8753 Event::SpendableOutputs { ref outputs } => {
8754 for outp in outputs {
8756 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8758 previous_output: outpoint.clone(),
8759 script_sig: Script::new(),
8761 witness: Vec::new(),
8764 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8765 value: output.value,
8767 let mut spend_tx = Transaction {
8773 let secp_ctx = Secp256k1::new();
8774 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8775 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8776 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8777 let remotesig = secp_ctx.sign(&sighash, key);
8778 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8779 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8780 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8783 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8785 previous_output: outpoint.clone(),
8786 script_sig: Script::new(),
8787 sequence: *to_self_delay as u32,
8788 witness: Vec::new(),
8791 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8792 value: output.value,
8794 let mut spend_tx = Transaction {
8800 let secp_ctx = Secp256k1::new();
8801 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8802 let local_delaysig = secp_ctx.sign(&sighash, key);
8803 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8804 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8805 spend_tx.input[0].witness.push(vec!(0));
8806 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8809 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8810 let secp_ctx = Secp256k1::new();
8812 previous_output: outpoint.clone(),
8813 script_sig: Script::new(),
8815 witness: Vec::new(),
8818 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8819 value: output.value,
8821 let mut spend_tx = Transaction {
8825 output: vec![outp.clone()],
8828 match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8830 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8832 Err(_) => panic!("Your RNG is busted"),
8835 Err(_) => panic!("Your rng is busted"),
8838 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8839 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8840 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8841 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8842 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8843 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8844 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8850 _ => panic!("Unexpected event"),
8859 fn test_claim_sizeable_push_msat() {
8860 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8861 let nodes = create_network(2);
8863 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8864 nodes[1].node.force_close_channel(&chan.2);
8865 let events = nodes[1].node.get_and_clear_pending_msg_events();
8867 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8868 _ => panic!("Unexpected event"),
8870 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8871 assert_eq!(node_txn.len(), 1);
8872 check_spends!(node_txn[0], chan.3.clone());
8873 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
8875 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8876 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8877 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8878 assert_eq!(spend_txn.len(), 1);
8879 check_spends!(spend_txn[0], node_txn[0].clone());
8883 fn test_claim_on_remote_sizeable_push_msat() {
8884 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8885 // to_remote output is encumbered by a P2WPKH
8887 let nodes = create_network(2);
8889 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8890 nodes[0].node.force_close_channel(&chan.2);
8891 let events = nodes[0].node.get_and_clear_pending_msg_events();
8893 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8894 _ => panic!("Unexpected event"),
8896 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8897 assert_eq!(node_txn.len(), 1);
8898 check_spends!(node_txn[0], chan.3.clone());
8899 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
8901 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8902 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8903 let events = nodes[1].node.get_and_clear_pending_msg_events();
8905 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8906 _ => panic!("Unexpected event"),
8908 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8909 assert_eq!(spend_txn.len(), 2);
8910 assert_eq!(spend_txn[0], spend_txn[1]);
8911 check_spends!(spend_txn[0], node_txn[0].clone());
8915 fn test_claim_on_remote_revoked_sizeable_push_msat() {
8916 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8917 // to_remote output is encumbered by a P2WPKH
8919 let nodes = create_network(2);
8921 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8922 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8923 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8924 assert_eq!(revoked_local_txn[0].input.len(), 1);
8925 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8927 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8928 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8929 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8930 let events = nodes[1].node.get_and_clear_pending_msg_events();
8932 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8933 _ => panic!("Unexpected event"),
8935 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8936 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8937 assert_eq!(spend_txn.len(), 4);
8938 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8939 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8940 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8941 check_spends!(spend_txn[1], node_txn[0].clone());
8945 fn test_static_spendable_outputs_preimage_tx() {
8946 let nodes = create_network(2);
8948 // Create some initial channels
8949 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8951 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8953 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8954 assert_eq!(commitment_tx[0].input.len(), 1);
8955 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8957 // Settle A's commitment tx on B's chain
8958 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8959 assert!(nodes[1].node.claim_funds(payment_preimage));
8960 check_added_monitors!(nodes[1], 1);
8961 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8962 let events = nodes[1].node.get_and_clear_pending_msg_events();
8964 MessageSendEvent::UpdateHTLCs { .. } => {},
8965 _ => panic!("Unexpected event"),
8968 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8969 _ => panic!("Unexepected event"),
8972 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8973 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8974 check_spends!(node_txn[0], commitment_tx[0].clone());
8975 assert_eq!(node_txn[0], node_txn[2]);
8976 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8977 check_spends!(node_txn[1], chan_1.3.clone());
8979 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8980 assert_eq!(spend_txn.len(), 2);
8981 assert_eq!(spend_txn[0], spend_txn[1]);
8982 check_spends!(spend_txn[0], node_txn[0].clone());
8986 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8987 let nodes = create_network(2);
8989 // Create some initial channels
8990 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8992 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8993 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8994 assert_eq!(revoked_local_txn[0].input.len(), 1);
8995 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8997 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8999 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9000 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9001 let events = nodes[1].node.get_and_clear_pending_msg_events();
9003 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9004 _ => panic!("Unexpected event"),
9006 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9007 assert_eq!(node_txn.len(), 3);
9008 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9009 assert_eq!(node_txn[0].input.len(), 2);
9010 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9012 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9013 assert_eq!(spend_txn.len(), 2);
9014 assert_eq!(spend_txn[0], spend_txn[1]);
9015 check_spends!(spend_txn[0], node_txn[0].clone());
9019 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9020 let nodes = create_network(2);
9022 // Create some initial channels
9023 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9025 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9026 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9027 assert_eq!(revoked_local_txn[0].input.len(), 1);
9028 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9030 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9032 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9033 // A will generate HTLC-Timeout from revoked commitment tx
9034 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9035 let events = nodes[0].node.get_and_clear_pending_msg_events();
9037 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9038 _ => panic!("Unexpected event"),
9040 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9041 assert_eq!(revoked_htlc_txn.len(), 3);
9042 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9043 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9044 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9045 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9046 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9048 // B will generate justice tx from A's revoked commitment/HTLC tx
9049 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9050 let events = nodes[1].node.get_and_clear_pending_msg_events();
9052 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9053 _ => panic!("Unexpected event"),
9056 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9057 assert_eq!(node_txn.len(), 4);
9058 assert_eq!(node_txn[3].input.len(), 1);
9059 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9061 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9062 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9063 assert_eq!(spend_txn.len(), 3);
9064 assert_eq!(spend_txn[0], spend_txn[1]);
9065 check_spends!(spend_txn[0], node_txn[0].clone());
9066 check_spends!(spend_txn[2], node_txn[3].clone());
9070 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9071 let nodes = create_network(2);
9073 // Create some initial channels
9074 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9076 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9077 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9078 assert_eq!(revoked_local_txn[0].input.len(), 1);
9079 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9081 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9083 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9084 // B will generate HTLC-Success from revoked commitment tx
9085 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9086 let events = nodes[1].node.get_and_clear_pending_msg_events();
9088 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9089 _ => panic!("Unexpected event"),
9091 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9093 assert_eq!(revoked_htlc_txn.len(), 3);
9094 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9095 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9096 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9097 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9099 // A will generate justice tx from B's revoked commitment/HTLC tx
9100 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9101 let events = nodes[0].node.get_and_clear_pending_msg_events();
9103 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9104 _ => panic!("Unexpected event"),
9107 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9108 assert_eq!(node_txn.len(), 4);
9109 assert_eq!(node_txn[3].input.len(), 1);
9110 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9112 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9113 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9114 assert_eq!(spend_txn.len(), 5);
9115 assert_eq!(spend_txn[0], spend_txn[2]);
9116 assert_eq!(spend_txn[1], spend_txn[3]);
9117 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9118 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9119 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9123 fn test_onchain_to_onchain_claim() {
9124 // Test that in case of channel closure, we detect the state of output thanks to
9125 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9126 // First, have C claim an HTLC against its own latest commitment transaction.
9127 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9129 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9132 let nodes = create_network(3);
9134 // Create some initial channels
9135 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9136 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9138 // Rebalance the network a bit by relaying one payment through all the channels ...
9139 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9140 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9142 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9143 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9144 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9145 check_spends!(commitment_tx[0], chan_2.3.clone());
9146 nodes[2].node.claim_funds(payment_preimage);
9147 check_added_monitors!(nodes[2], 1);
9148 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9149 assert!(updates.update_add_htlcs.is_empty());
9150 assert!(updates.update_fail_htlcs.is_empty());
9151 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9152 assert!(updates.update_fail_malformed_htlcs.is_empty());
9154 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9155 let events = nodes[2].node.get_and_clear_pending_msg_events();
9156 assert_eq!(events.len(), 1);
9158 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9159 _ => panic!("Unexpected event"),
9162 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9163 assert_eq!(c_txn.len(), 3);
9164 assert_eq!(c_txn[0], c_txn[2]);
9165 assert_eq!(commitment_tx[0], c_txn[1]);
9166 check_spends!(c_txn[1], chan_2.3.clone());
9167 check_spends!(c_txn[2], c_txn[1].clone());
9168 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9169 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9170 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9171 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9173 // 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
9174 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9176 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9177 assert_eq!(b_txn.len(), 4);
9178 assert_eq!(b_txn[0], b_txn[3]);
9179 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9180 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9181 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9182 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9183 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9184 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9185 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9186 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9187 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9190 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9191 check_added_monitors!(nodes[1], 1);
9192 match msg_events[0] {
9193 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9194 _ => panic!("Unexpected event"),
9196 match msg_events[1] {
9197 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, .. } } => {
9198 assert!(update_add_htlcs.is_empty());
9199 assert!(update_fail_htlcs.is_empty());
9200 assert_eq!(update_fulfill_htlcs.len(), 1);
9201 assert!(update_fail_malformed_htlcs.is_empty());
9202 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9204 _ => panic!("Unexpected event"),
9206 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9207 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9208 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9209 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9210 assert_eq!(b_txn.len(), 3);
9211 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9212 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9213 check_spends!(b_txn[0], commitment_tx[0].clone());
9214 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9215 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9216 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9217 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9218 match msg_events[0] {
9219 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9220 _ => panic!("Unexpected event"),
9225 fn test_duplicate_payment_hash_one_failure_one_success() {
9226 // Topology : A --> B --> C
9227 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9228 let mut nodes = create_network(3);
9230 create_announced_chan_between_nodes(&nodes, 0, 1);
9231 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9233 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9234 *nodes[0].network_payment_count.borrow_mut() -= 1;
9235 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9237 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9238 assert_eq!(commitment_txn[0].input.len(), 1);
9239 check_spends!(commitment_txn[0], chan_2.3.clone());
9241 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9242 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9243 let htlc_timeout_tx;
9244 { // Extract one of the two HTLC-Timeout transaction
9245 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9246 assert_eq!(node_txn.len(), 7);
9247 assert_eq!(node_txn[0], node_txn[5]);
9248 assert_eq!(node_txn[1], node_txn[6]);
9249 check_spends!(node_txn[0], commitment_txn[0].clone());
9250 assert_eq!(node_txn[0].input.len(), 1);
9251 check_spends!(node_txn[1], commitment_txn[0].clone());
9252 assert_eq!(node_txn[1].input.len(), 1);
9253 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9254 check_spends!(node_txn[2], chan_2.3.clone());
9255 check_spends!(node_txn[3], node_txn[2].clone());
9256 check_spends!(node_txn[4], node_txn[2].clone());
9257 htlc_timeout_tx = node_txn[1].clone();
9260 let events = nodes[1].node.get_and_clear_pending_msg_events();
9262 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9263 _ => panic!("Unexepected event"),
9266 nodes[2].node.claim_funds(our_payment_preimage);
9267 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9268 check_added_monitors!(nodes[2], 2);
9269 let events = nodes[2].node.get_and_clear_pending_msg_events();
9271 MessageSendEvent::UpdateHTLCs { .. } => {},
9272 _ => panic!("Unexpected event"),
9275 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9276 _ => panic!("Unexepected event"),
9278 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9279 assert_eq!(htlc_success_txn.len(), 5);
9280 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9281 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9282 assert_eq!(htlc_success_txn[0].input.len(), 1);
9283 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9284 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9285 assert_eq!(htlc_success_txn[1].input.len(), 1);
9286 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9287 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9288 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9289 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9291 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9292 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9293 assert!(htlc_updates.update_add_htlcs.is_empty());
9294 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9295 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9296 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9297 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9298 check_added_monitors!(nodes[1], 1);
9300 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9301 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9303 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9304 let events = nodes[0].node.get_and_clear_pending_msg_events();
9305 assert_eq!(events.len(), 1);
9307 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
9309 _ => { panic!("Unexpected event"); }
9312 let events = nodes[0].node.get_and_clear_pending_events();
9314 Event::PaymentFailed { ref payment_hash, .. } => {
9315 assert_eq!(*payment_hash, duplicate_payment_hash);
9317 _ => panic!("Unexpected event"),
9320 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9321 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9322 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9323 assert!(updates.update_add_htlcs.is_empty());
9324 assert!(updates.update_fail_htlcs.is_empty());
9325 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9326 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9327 assert!(updates.update_fail_malformed_htlcs.is_empty());
9328 check_added_monitors!(nodes[1], 1);
9330 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9331 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9333 let events = nodes[0].node.get_and_clear_pending_events();
9335 Event::PaymentSent { ref payment_preimage } => {
9336 assert_eq!(*payment_preimage, our_payment_preimage);
9338 _ => panic!("Unexpected event"),
9343 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9344 let nodes = create_network(2);
9346 // Create some initial channels
9347 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9349 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9350 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9351 assert_eq!(local_txn[0].input.len(), 1);
9352 check_spends!(local_txn[0], chan_1.3.clone());
9354 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9355 nodes[1].node.claim_funds(payment_preimage);
9356 check_added_monitors!(nodes[1], 1);
9357 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9358 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9359 let events = nodes[1].node.get_and_clear_pending_msg_events();
9361 MessageSendEvent::UpdateHTLCs { .. } => {},
9362 _ => panic!("Unexpected event"),
9365 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9366 _ => panic!("Unexepected event"),
9368 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9369 assert_eq!(node_txn[0].input.len(), 1);
9370 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9371 check_spends!(node_txn[0], local_txn[0].clone());
9373 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9374 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9375 assert_eq!(spend_txn.len(), 2);
9376 check_spends!(spend_txn[0], node_txn[0].clone());
9377 check_spends!(spend_txn[1], node_txn[2].clone());
9381 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9382 let nodes = create_network(2);
9384 // Create some initial channels
9385 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9387 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9388 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9389 assert_eq!(local_txn[0].input.len(), 1);
9390 check_spends!(local_txn[0], chan_1.3.clone());
9392 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9393 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9394 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9395 let events = nodes[0].node.get_and_clear_pending_msg_events();
9397 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9398 _ => panic!("Unexepected event"),
9400 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9401 assert_eq!(node_txn[0].input.len(), 1);
9402 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9403 check_spends!(node_txn[0], local_txn[0].clone());
9405 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9406 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9407 assert_eq!(spend_txn.len(), 8);
9408 assert_eq!(spend_txn[0], spend_txn[2]);
9409 assert_eq!(spend_txn[0], spend_txn[4]);
9410 assert_eq!(spend_txn[0], spend_txn[6]);
9411 assert_eq!(spend_txn[1], spend_txn[3]);
9412 assert_eq!(spend_txn[1], spend_txn[5]);
9413 assert_eq!(spend_txn[1], spend_txn[7]);
9414 check_spends!(spend_txn[0], local_txn[0].clone());
9415 check_spends!(spend_txn[1], node_txn[0].clone());
9419 fn test_static_output_closing_tx() {
9420 let nodes = create_network(2);
9422 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9424 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9425 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9427 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9428 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9429 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9430 assert_eq!(spend_txn.len(), 1);
9431 check_spends!(spend_txn[0], closing_tx.clone());
9433 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9434 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9435 assert_eq!(spend_txn.len(), 1);
9436 check_spends!(spend_txn[0], closing_tx);