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, HTLC_FAIL_ANTI_REORG_DELAY};
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;
40 use crypto::mac::{Mac,MacResult};
41 use crypto::hmac::Hmac;
42 use crypto::digest::Digest;
43 use crypto::symmetriccipher::SynchronousStreamCipher;
45 use std::{cmp, ptr, mem};
46 use std::collections::{HashMap, hash_map, HashSet};
48 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
49 use std::sync::atomic::{AtomicUsize, Ordering};
50 use std::time::{Instant,Duration};
52 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
54 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
55 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
56 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
58 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
59 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
60 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
61 /// the HTLC backwards along the relevant path).
62 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
63 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
64 mod channel_held_info {
66 use ln::router::Route;
67 use ln::channelmanager::PaymentHash;
68 use secp256k1::key::SecretKey;
70 /// Stores the info we will need to send when we want to forward an HTLC onwards
71 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
72 pub struct PendingForwardHTLCInfo {
73 pub(super) onion_packet: Option<msgs::OnionPacket>,
74 pub(super) incoming_shared_secret: [u8; 32],
75 pub(super) payment_hash: PaymentHash,
76 pub(super) short_channel_id: u64,
77 pub(super) amt_to_forward: u64,
78 pub(super) outgoing_cltv_value: u32,
81 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
82 pub enum HTLCFailureMsg {
83 Relay(msgs::UpdateFailHTLC),
84 Malformed(msgs::UpdateFailMalformedHTLC),
87 /// Stores whether we can't forward an HTLC or relevant forwarding info
88 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
89 pub enum PendingHTLCStatus {
90 Forward(PendingForwardHTLCInfo),
94 /// Tracks the inbound corresponding to an outbound HTLC
95 #[derive(Clone, PartialEq)]
96 pub struct HTLCPreviousHopData {
97 pub(super) short_channel_id: u64,
98 pub(super) htlc_id: u64,
99 pub(super) incoming_packet_shared_secret: [u8; 32],
102 /// Tracks the inbound corresponding to an outbound HTLC
103 #[derive(Clone, PartialEq)]
104 pub enum HTLCSource {
105 PreviousHopData(HTLCPreviousHopData),
108 session_priv: SecretKey,
109 /// Technically we can recalculate this from the route, but we cache it here to avoid
110 /// doing a double-pass on route when we get a failure back
111 first_hop_htlc_msat: u64,
116 pub fn dummy() -> Self {
117 HTLCSource::OutboundRoute {
118 route: Route { hops: Vec::new() },
119 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
120 first_hop_htlc_msat: 0,
125 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
126 pub(crate) enum HTLCFailReason {
128 err: msgs::OnionErrorPacket,
136 pub(super) use self::channel_held_info::*;
138 /// payment_hash type, use to cross-lock hop
139 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
140 pub struct PaymentHash(pub [u8;32]);
141 /// payment_preimage type, use to route payment between hop
142 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
143 pub struct PaymentPreimage(pub [u8;32]);
145 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
147 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
148 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
149 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
150 /// channel_state lock. We then return the set of things that need to be done outside the lock in
151 /// this struct and call handle_error!() on it.
153 struct MsgHandleErrInternal {
154 err: msgs::HandleError,
155 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
157 impl MsgHandleErrInternal {
159 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
163 action: Some(msgs::ErrorAction::SendErrorMessage {
164 msg: msgs::ErrorMessage {
166 data: err.to_string()
170 shutdown_finish: None,
174 fn from_no_close(err: msgs::HandleError) -> Self {
175 Self { err, shutdown_finish: None }
178 fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
182 action: Some(msgs::ErrorAction::SendErrorMessage {
183 msg: msgs::ErrorMessage {
185 data: err.to_string()
189 shutdown_finish: Some((shutdown_res, channel_update)),
193 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
196 ChannelError::Ignore(msg) => HandleError {
198 action: Some(msgs::ErrorAction::IgnoreError),
200 ChannelError::Close(msg) => HandleError {
202 action: Some(msgs::ErrorAction::SendErrorMessage {
203 msg: msgs::ErrorMessage {
205 data: msg.to_string()
210 shutdown_finish: None,
215 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
216 /// after a PaymentReceived event.
218 pub enum PaymentFailReason {
219 /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
221 /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
225 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
226 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
227 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
228 /// probably increase this significantly.
229 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
231 struct HTLCForwardInfo {
232 prev_short_channel_id: u64,
234 forward_info: PendingForwardHTLCInfo,
237 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
238 /// be sent in the order they appear in the return value, however sometimes the order needs to be
239 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
240 /// they were originally sent). In those cases, this enum is also returned.
241 #[derive(Clone, PartialEq)]
242 pub(super) enum RAACommitmentOrder {
243 /// Send the CommitmentUpdate messages first
245 /// Send the RevokeAndACK message first
249 struct ChannelHolder {
250 by_id: HashMap<[u8; 32], Channel>,
251 short_to_id: HashMap<u64, [u8; 32]>,
252 next_forward: Instant,
253 /// short channel id -> forward infos. Key of 0 means payments received
254 /// Note that while this is held in the same mutex as the channels themselves, no consistency
255 /// guarantees are made about there existing a channel with the short id here, nor the short
256 /// ids in the PendingForwardHTLCInfo!
257 forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
258 /// Note that while this is held in the same mutex as the channels themselves, no consistency
259 /// guarantees are made about the channels given here actually existing anymore by the time you
261 claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
262 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
263 /// for broadcast messages, where ordering isn't as strict).
264 pending_msg_events: Vec<events::MessageSendEvent>,
266 struct MutChannelHolder<'a> {
267 by_id: &'a mut HashMap<[u8; 32], Channel>,
268 short_to_id: &'a mut HashMap<u64, [u8; 32]>,
269 next_forward: &'a mut Instant,
270 forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
271 claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
272 pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
275 fn borrow_parts(&mut self) -> MutChannelHolder {
277 by_id: &mut self.by_id,
278 short_to_id: &mut self.short_to_id,
279 next_forward: &mut self.next_forward,
280 forward_htlcs: &mut self.forward_htlcs,
281 claimable_htlcs: &mut self.claimable_htlcs,
282 pending_msg_events: &mut self.pending_msg_events,
287 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
288 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
290 /// Manager which keeps track of a number of channels and sends messages to the appropriate
291 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
293 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
294 /// to individual Channels.
296 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
297 /// all peers during write/read (though does not modify this instance, only the instance being
298 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
299 /// called funding_transaction_generated for outbound channels).
301 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
302 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
303 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
304 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
305 /// the serialization process). If the deserialized version is out-of-date compared to the
306 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
307 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
309 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
310 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
311 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
312 /// block_connected() to step towards your best block) upon deserialization before using the
314 pub struct ChannelManager {
315 default_configuration: UserConfig,
316 genesis_hash: Sha256dHash,
317 fee_estimator: Arc<FeeEstimator>,
318 monitor: Arc<ManyChannelMonitor>,
319 chain_monitor: Arc<ChainWatchInterface>,
320 tx_broadcaster: Arc<BroadcasterInterface>,
322 latest_block_height: AtomicUsize,
323 last_block_hash: Mutex<Sha256dHash>,
324 secp_ctx: Secp256k1<secp256k1::All>,
326 channel_state: Mutex<ChannelHolder>,
327 our_network_key: SecretKey,
329 pending_events: Mutex<Vec<events::Event>>,
330 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
331 /// Essentially just when we're serializing ourselves out.
332 /// Taken first everywhere where we are making changes before any other locks.
333 total_consistency_lock: RwLock<()>,
335 keys_manager: Arc<KeysInterface>,
340 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
341 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
342 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
343 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
344 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
345 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
346 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
348 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
349 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
350 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
351 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
352 // on-chain to time out the HTLC.
355 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
357 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
358 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
361 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
363 macro_rules! secp_call {
364 ( $res: expr, $err: expr ) => {
367 Err(_) => return Err($err),
374 shared_secret: SharedSecret,
376 blinding_factor: [u8; 32],
377 ephemeral_pubkey: PublicKey,
382 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
383 pub struct ChannelDetails {
384 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
385 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
386 /// Note that this means this value is *not* persistent - it can change once during the
387 /// lifetime of the channel.
388 pub channel_id: [u8; 32],
389 /// The position of the funding transaction in the chain. None if the funding transaction has
390 /// not yet been confirmed and the channel fully opened.
391 pub short_channel_id: Option<u64>,
392 /// The node_id of our counterparty
393 pub remote_network_id: PublicKey,
394 /// The value, in satoshis, of this channel as appears in the funding output
395 pub channel_value_satoshis: u64,
396 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
400 macro_rules! handle_error {
401 ($self: ident, $internal: expr, $their_node_id: expr) => {
404 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
405 if let Some((shutdown_res, update_option)) = shutdown_finish {
406 $self.finish_force_close_channel(shutdown_res);
407 if let Some(update) = update_option {
408 let mut channel_state = $self.channel_state.lock().unwrap();
409 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
420 macro_rules! break_chan_entry {
421 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
424 Err(ChannelError::Ignore(msg)) => {
425 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
427 Err(ChannelError::Close(msg)) => {
428 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
429 let (channel_id, mut chan) = $entry.remove_entry();
430 if let Some(short_id) = chan.get_short_channel_id() {
431 $channel_state.short_to_id.remove(&short_id);
433 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
439 macro_rules! try_chan_entry {
440 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
443 Err(ChannelError::Ignore(msg)) => {
444 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
446 Err(ChannelError::Close(msg)) => {
447 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
448 let (channel_id, mut chan) = $entry.remove_entry();
449 if let Some(short_id) = chan.get_short_channel_id() {
450 $channel_state.short_to_id.remove(&short_id);
452 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
458 macro_rules! return_monitor_err {
459 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
460 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
462 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
463 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
464 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
466 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
467 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
469 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
471 ChannelMonitorUpdateErr::PermanentFailure => {
472 let (channel_id, mut chan) = $entry.remove_entry();
473 if let Some(short_id) = chan.get_short_channel_id() {
474 $channel_state.short_to_id.remove(&short_id);
476 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
477 // chain in a confused state! We need to move them into the ChannelMonitor which
478 // will be responsible for failing backwards once things confirm on-chain.
479 // It's ok that we drop $failed_forwards here - at this point we'd rather they
480 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
481 // us bother trying to claim it just to forward on to another peer. If we're
482 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
483 // given up the preimage yet, so might as well just wait until the payment is
484 // retried, avoiding the on-chain fees.
485 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
487 ChannelMonitorUpdateErr::TemporaryFailure => {
488 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
489 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
495 // Does not break in case of TemporaryFailure!
496 macro_rules! maybe_break_monitor_err {
497 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
499 ChannelMonitorUpdateErr::PermanentFailure => {
500 let (channel_id, mut chan) = $entry.remove_entry();
501 if let Some(short_id) = chan.get_short_channel_id() {
502 $channel_state.short_to_id.remove(&short_id);
504 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
506 ChannelMonitorUpdateErr::TemporaryFailure => {
507 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
513 impl ChannelManager {
514 /// Constructs a new ChannelManager to hold several channels and route between them.
516 /// This is the main "logic hub" for all channel-related actions, and implements
517 /// ChannelMessageHandler.
519 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
521 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
522 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> {
523 let secp_ctx = Secp256k1::new();
525 let res = Arc::new(ChannelManager {
526 default_configuration: config.clone(),
527 genesis_hash: genesis_block(network).header.bitcoin_hash(),
528 fee_estimator: feeest.clone(),
529 monitor: monitor.clone(),
533 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
534 last_block_hash: Mutex::new(Default::default()),
537 channel_state: Mutex::new(ChannelHolder{
538 by_id: HashMap::new(),
539 short_to_id: HashMap::new(),
540 next_forward: Instant::now(),
541 forward_htlcs: HashMap::new(),
542 claimable_htlcs: HashMap::new(),
543 pending_msg_events: Vec::new(),
545 our_network_key: keys_manager.get_node_secret(),
547 pending_events: Mutex::new(Vec::new()),
548 total_consistency_lock: RwLock::new(()),
554 let weak_res = Arc::downgrade(&res);
555 res.chain_monitor.register_listener(weak_res);
559 /// Creates a new outbound channel to the given remote node and with the given value.
561 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
562 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
563 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
564 /// may wish to avoid using 0 for user_id here.
566 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
567 /// PeerManager::process_events afterwards.
569 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
570 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
571 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
572 if channel_value_satoshis < 1000 {
573 return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
576 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)?;
577 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
579 let _ = self.total_consistency_lock.read().unwrap();
580 let mut channel_state = self.channel_state.lock().unwrap();
581 match channel_state.by_id.entry(channel.channel_id()) {
582 hash_map::Entry::Occupied(_) => {
583 if cfg!(feature = "fuzztarget") {
584 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
586 panic!("RNG is bad???");
589 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
591 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
592 node_id: their_network_key,
598 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
599 /// more information.
600 pub fn list_channels(&self) -> Vec<ChannelDetails> {
601 let channel_state = self.channel_state.lock().unwrap();
602 let mut res = Vec::with_capacity(channel_state.by_id.len());
603 for (channel_id, channel) in channel_state.by_id.iter() {
604 res.push(ChannelDetails {
605 channel_id: (*channel_id).clone(),
606 short_channel_id: channel.get_short_channel_id(),
607 remote_network_id: channel.get_their_node_id(),
608 channel_value_satoshis: channel.get_value_satoshis(),
609 user_id: channel.get_user_id(),
615 /// Gets the list of usable channels, in random order. Useful as an argument to
616 /// Router::get_route to ensure non-announced channels are used.
617 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
618 let channel_state = self.channel_state.lock().unwrap();
619 let mut res = Vec::with_capacity(channel_state.by_id.len());
620 for (channel_id, channel) in channel_state.by_id.iter() {
621 // Note we use is_live here instead of usable which leads to somewhat confused
622 // internal/external nomenclature, but that's ok cause that's probably what the user
623 // really wanted anyway.
624 if channel.is_live() {
625 res.push(ChannelDetails {
626 channel_id: (*channel_id).clone(),
627 short_channel_id: channel.get_short_channel_id(),
628 remote_network_id: channel.get_their_node_id(),
629 channel_value_satoshis: channel.get_value_satoshis(),
630 user_id: channel.get_user_id(),
637 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
638 /// will be accepted on the given channel, and after additional timeout/the closing of all
639 /// pending HTLCs, the channel will be closed on chain.
641 /// May generate a SendShutdown message event on success, which should be relayed.
642 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
643 let _ = self.total_consistency_lock.read().unwrap();
645 let (mut failed_htlcs, chan_option) = {
646 let mut channel_state_lock = self.channel_state.lock().unwrap();
647 let channel_state = channel_state_lock.borrow_parts();
648 match channel_state.by_id.entry(channel_id.clone()) {
649 hash_map::Entry::Occupied(mut chan_entry) => {
650 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
651 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
652 node_id: chan_entry.get().get_their_node_id(),
655 if chan_entry.get().is_shutdown() {
656 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
657 channel_state.short_to_id.remove(&short_id);
659 (failed_htlcs, Some(chan_entry.remove_entry().1))
660 } else { (failed_htlcs, None) }
662 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
665 for htlc_source in failed_htlcs.drain(..) {
666 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
668 let chan_update = if let Some(chan) = chan_option {
669 if let Ok(update) = self.get_channel_update(&chan) {
674 if let Some(update) = chan_update {
675 let mut channel_state = self.channel_state.lock().unwrap();
676 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
685 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
686 let (local_txn, mut failed_htlcs) = shutdown_res;
687 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
688 for htlc_source in failed_htlcs.drain(..) {
689 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
691 for tx in local_txn {
692 self.tx_broadcaster.broadcast_transaction(&tx);
696 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
697 /// the chain and rejecting new HTLCs on the given channel.
698 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
699 let _ = self.total_consistency_lock.read().unwrap();
702 let mut channel_state_lock = self.channel_state.lock().unwrap();
703 let channel_state = channel_state_lock.borrow_parts();
704 if let Some(chan) = channel_state.by_id.remove(channel_id) {
705 if let Some(short_id) = chan.get_short_channel_id() {
706 channel_state.short_to_id.remove(&short_id);
713 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
714 self.finish_force_close_channel(chan.force_shutdown());
715 if let Ok(update) = self.get_channel_update(&chan) {
716 let mut channel_state = self.channel_state.lock().unwrap();
717 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
723 /// Force close all channels, immediately broadcasting the latest local commitment transaction
724 /// for each to the chain and rejecting new HTLCs on each.
725 pub fn force_close_all_channels(&self) {
726 for chan in self.list_channels() {
727 self.force_close_channel(&chan.channel_id);
732 fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
733 assert_eq!(shared_secret.len(), 32);
735 let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
736 hmac.input(&shared_secret[..]);
737 let mut res = [0; 32];
738 hmac.raw_result(&mut res);
742 let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
743 hmac.input(&shared_secret[..]);
744 let mut res = [0; 32];
745 hmac.raw_result(&mut res);
751 fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
752 assert_eq!(shared_secret.len(), 32);
753 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
754 hmac.input(&shared_secret[..]);
755 let mut res = [0; 32];
756 hmac.raw_result(&mut res);
761 fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
762 assert_eq!(shared_secret.len(), 32);
763 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
764 hmac.input(&shared_secret[..]);
765 let mut res = [0; 32];
766 hmac.raw_result(&mut res);
770 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
772 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> {
773 let mut blinded_priv = session_priv.clone();
774 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
776 for hop in route.hops.iter() {
777 let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
779 let mut sha = Sha256::new();
780 sha.input(&blinded_pub.serialize()[..]);
781 sha.input(&shared_secret[..]);
782 let mut blinding_factor = [0u8; 32];
783 sha.result(&mut blinding_factor);
785 let ephemeral_pubkey = blinded_pub;
787 blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
788 blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
790 callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
796 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
797 fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
798 let mut res = Vec::with_capacity(route.hops.len());
800 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
801 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
807 blinding_factor: _blinding_factor,
817 /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
818 fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
819 let mut cur_value_msat = 0u64;
820 let mut cur_cltv = starting_htlc_offset;
821 let mut last_short_channel_id = 0;
822 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
823 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
824 unsafe { res.set_len(route.hops.len()); }
826 for (idx, hop) in route.hops.iter().enumerate().rev() {
827 // First hop gets special values so that it can check, on receipt, that everything is
828 // exactly as it should be (and the next hop isn't trying to probe to find out if we're
829 // the intended recipient).
830 let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
831 let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
832 res[idx] = msgs::OnionHopData {
834 data: msgs::OnionRealm0HopData {
835 short_channel_id: last_short_channel_id,
836 amt_to_forward: value_msat,
837 outgoing_cltv_value: cltv,
841 cur_value_msat += hop.fee_msat;
842 if cur_value_msat >= 21000000 * 100000000 * 1000 {
843 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
845 cur_cltv += hop.cltv_expiry_delta as u32;
846 if cur_cltv >= 500000000 {
847 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
849 last_short_channel_id = hop.short_channel_id;
851 Ok((res, cur_value_msat, cur_cltv))
855 fn shift_arr_right(arr: &mut [u8; 20*65]) {
857 ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
865 fn xor_bufs(dst: &mut[u8], src: &[u8]) {
866 assert_eq!(dst.len(), src.len());
868 for i in 0..dst.len() {
873 const ZERO:[u8; 21*65] = [0; 21*65];
874 fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
875 let mut buf = Vec::with_capacity(21*65);
876 buf.resize(21*65, 0);
879 let iters = payloads.len() - 1;
880 let end_len = iters * 65;
881 let mut res = Vec::with_capacity(end_len);
882 res.resize(end_len, 0);
884 for (i, keys) in onion_keys.iter().enumerate() {
885 if i == payloads.len() - 1 { continue; }
886 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
887 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
888 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
893 let mut packet_data = [0; 20*65];
894 let mut hmac_res = [0; 32];
896 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
897 ChannelManager::shift_arr_right(&mut packet_data);
898 payload.hmac = hmac_res;
899 packet_data[0..65].copy_from_slice(&payload.encode()[..]);
901 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
902 chacha.process(&packet_data, &mut buf[0..20*65]);
903 packet_data[..].copy_from_slice(&buf[0..20*65]);
906 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
909 let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
910 hmac.input(&packet_data);
911 hmac.input(&associated_data.0[..]);
912 hmac.raw_result(&mut hmac_res);
917 public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
918 hop_data: packet_data,
923 /// Encrypts a failure packet. raw_packet can either be a
924 /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
925 fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
926 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
928 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
929 packet_crypted.resize(raw_packet.len(), 0);
930 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
931 chacha.process(&raw_packet, &mut packet_crypted[..]);
932 msgs::OnionErrorPacket {
933 data: packet_crypted,
937 fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
938 assert_eq!(shared_secret.len(), 32);
939 assert!(failure_data.len() <= 256 - 2);
941 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
944 let mut res = Vec::with_capacity(2 + failure_data.len());
945 res.push(((failure_type >> 8) & 0xff) as u8);
946 res.push(((failure_type >> 0) & 0xff) as u8);
947 res.extend_from_slice(&failure_data[..]);
951 let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
952 res.resize(256 - 2 - failure_data.len(), 0);
955 let mut packet = msgs::DecodedOnionErrorPacket {
957 failuremsg: failuremsg,
961 let mut hmac = Hmac::new(Sha256::new(), &um);
962 hmac.input(&packet.encode()[32..]);
963 hmac.raw_result(&mut packet.hmac);
969 fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
970 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
971 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
974 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
975 macro_rules! get_onion_hash {
978 let mut sha = Sha256::new();
979 sha.input(&msg.onion_routing_packet.hop_data);
980 let mut onion_hash = [0; 32];
981 sha.result(&mut onion_hash);
987 if let Err(_) = msg.onion_routing_packet.public_key {
988 log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
989 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
990 channel_id: msg.channel_id,
991 htlc_id: msg.htlc_id,
992 sha256_of_onion: get_onion_hash!(),
993 failure_code: 0x8000 | 0x4000 | 6,
994 })), self.channel_state.lock().unwrap());
997 let shared_secret = {
998 let mut arr = [0; 32];
999 arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1002 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1004 let mut channel_state = None;
1005 macro_rules! return_err {
1006 ($msg: expr, $err_code: expr, $data: expr) => {
1008 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1009 if channel_state.is_none() {
1010 channel_state = Some(self.channel_state.lock().unwrap());
1012 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1013 channel_id: msg.channel_id,
1014 htlc_id: msg.htlc_id,
1015 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1016 })), channel_state.unwrap());
1021 if msg.onion_routing_packet.version != 0 {
1022 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1023 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1024 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1025 //receiving node would have to brute force to figure out which version was put in the
1026 //packet by the node that send us the message, in the case of hashing the hop_data, the
1027 //node knows the HMAC matched, so they already know what is there...
1028 return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1031 let mut hmac = Hmac::new(Sha256::new(), &mu);
1032 hmac.input(&msg.onion_routing_packet.hop_data);
1033 hmac.input(&msg.payment_hash.0[..]);
1034 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1035 return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1038 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1039 let next_hop_data = {
1040 let mut decoded = [0; 65];
1041 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1042 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1044 let error_code = match err {
1045 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1046 _ => 0x2000 | 2, // Should never happen
1048 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1054 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1056 // final_expiry_too_soon
1057 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1058 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1060 // final_incorrect_htlc_amount
1061 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1062 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1064 // final_incorrect_cltv_expiry
1065 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1066 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1069 // Note that we could obviously respond immediately with an update_fulfill_htlc
1070 // message, however that would leak that we are the recipient of this payment, so
1071 // instead we stay symmetric with the forwarding case, only responding (after a
1072 // delay) once they've send us a commitment_signed!
1074 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1076 payment_hash: msg.payment_hash.clone(),
1077 short_channel_id: 0,
1078 incoming_shared_secret: shared_secret,
1079 amt_to_forward: next_hop_data.data.amt_to_forward,
1080 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1083 let mut new_packet_data = [0; 20*65];
1084 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1085 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1087 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1089 let blinding_factor = {
1090 let mut sha = Sha256::new();
1091 sha.input(&new_pubkey.serialize()[..]);
1092 sha.input(&shared_secret);
1093 let mut res = [0u8; 32];
1094 sha.result(&mut res);
1095 match SecretKey::from_slice(&self.secp_ctx, &res) {
1097 return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1103 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1104 return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1107 let outgoing_packet = msgs::OnionPacket {
1109 public_key: Ok(new_pubkey),
1110 hop_data: new_packet_data,
1111 hmac: next_hop_data.hmac.clone(),
1114 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1115 onion_packet: Some(outgoing_packet),
1116 payment_hash: msg.payment_hash.clone(),
1117 short_channel_id: next_hop_data.data.short_channel_id,
1118 incoming_shared_secret: shared_secret,
1119 amt_to_forward: next_hop_data.data.amt_to_forward,
1120 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1124 channel_state = Some(self.channel_state.lock().unwrap());
1125 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1126 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1127 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1128 let forwarding_id = match id_option {
1129 None => { // unknown_next_peer
1130 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1132 Some(id) => id.clone(),
1134 if let Some((err, code, chan_update)) = loop {
1135 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1137 // Note that we could technically not return an error yet here and just hope
1138 // that the connection is reestablished or monitor updated by the time we get
1139 // around to doing the actual forward, but better to fail early if we can and
1140 // hopefully an attacker trying to path-trace payments cannot make this occur
1141 // on a small/per-node/per-channel scale.
1142 if !chan.is_live() { // channel_disabled
1143 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1145 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1146 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1148 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) });
1149 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1150 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())));
1152 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1153 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())));
1155 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1156 // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1157 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1158 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1160 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1161 break Some(("CLTV expiry is too far in the future", 21, None));
1166 let mut res = Vec::with_capacity(8 + 128);
1167 if let Some(chan_update) = chan_update {
1168 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1169 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1171 else if code == 0x1000 | 13 {
1172 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1174 else if code == 0x1000 | 20 {
1175 res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1177 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1179 return_err!(err, code, &res[..]);
1184 (pending_forward_info, channel_state.unwrap())
1187 /// only fails if the channel does not yet have an assigned short_id
1188 /// May be called with channel_state already locked!
1189 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1190 let short_channel_id = match chan.get_short_channel_id() {
1191 None => return Err(HandleError{err: "Channel not yet established", action: None}),
1195 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1197 let unsigned = msgs::UnsignedChannelUpdate {
1198 chain_hash: self.genesis_hash,
1199 short_channel_id: short_channel_id,
1200 timestamp: chan.get_channel_update_count(),
1201 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1202 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1203 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1204 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1205 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1206 excess_data: Vec::new(),
1209 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1210 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1212 Ok(msgs::ChannelUpdate {
1218 /// Sends a payment along a given route.
1220 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1221 /// fields for more info.
1223 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1224 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1225 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1226 /// specified in the last hop in the route! Thus, you should probably do your own
1227 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1228 /// payment") and prevent double-sends yourself.
1230 /// May generate a SendHTLCs message event on success, which should be relayed.
1232 /// Raises APIError::RoutError when invalid route or forward parameter
1233 /// (cltv_delta, fee, node public key) is specified.
1234 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1235 /// (including due to previous monitor update failure or new permanent monitor update failure).
1236 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1237 /// relevant updates.
1239 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1240 /// and you may wish to retry via a different route immediately.
1241 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1242 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1243 /// the payment via a different route unless you intend to pay twice!
1244 pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1245 if route.hops.len() < 1 || route.hops.len() > 20 {
1246 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1248 let our_node_id = self.get_our_node_id();
1249 for (idx, hop) in route.hops.iter().enumerate() {
1250 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1251 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1255 let session_priv = self.keys_manager.get_session_key();
1257 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1259 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1260 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1261 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1262 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1264 let _ = self.total_consistency_lock.read().unwrap();
1266 let err: Result<(), _> = loop {
1267 let mut channel_lock = self.channel_state.lock().unwrap();
1269 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1270 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1271 Some(id) => id.clone(),
1274 let channel_state = channel_lock.borrow_parts();
1275 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1277 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1278 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1280 if !chan.get().is_live() {
1281 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1283 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1284 route: route.clone(),
1285 session_priv: session_priv.clone(),
1286 first_hop_htlc_msat: htlc_msat,
1287 }, onion_packet), channel_state, chan)
1289 Some((update_add, commitment_signed, chan_monitor)) => {
1290 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1291 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1292 // Note that MonitorUpdateFailed here indicates (per function docs)
1293 // that we will resent the commitment update once we unfree monitor
1294 // updating, so we have to take special care that we don't return
1295 // something else in case we will resend later!
1296 return Err(APIError::MonitorUpdateFailed);
1299 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1300 node_id: route.hops.first().unwrap().pubkey,
1301 updates: msgs::CommitmentUpdate {
1302 update_add_htlcs: vec![update_add],
1303 update_fulfill_htlcs: Vec::new(),
1304 update_fail_htlcs: Vec::new(),
1305 update_fail_malformed_htlcs: Vec::new(),
1313 } else { unreachable!(); }
1317 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1318 Ok(_) => unreachable!(),
1320 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1322 log_error!(self, "Got bad keys: {}!", e.err);
1323 let mut channel_state = self.channel_state.lock().unwrap();
1324 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1325 node_id: route.hops.first().unwrap().pubkey,
1329 Err(APIError::ChannelUnavailable { err: e.err })
1334 /// Call this upon creation of a funding transaction for the given channel.
1336 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1337 /// or your counterparty can steal your funds!
1339 /// Panics if a funding transaction has already been provided for this channel.
1341 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1342 /// be trivially prevented by using unique funding transaction keys per-channel).
1343 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1344 let _ = self.total_consistency_lock.read().unwrap();
1346 let (chan, msg, chan_monitor) = {
1348 let mut channel_state = self.channel_state.lock().unwrap();
1349 match channel_state.by_id.remove(temporary_channel_id) {
1351 (chan.get_outbound_funding_created(funding_txo)
1352 .map_err(|e| if let ChannelError::Close(msg) = e {
1353 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1354 } else { unreachable!(); })
1360 match handle_error!(self, res, chan.get_their_node_id()) {
1361 Ok(funding_msg) => {
1362 (chan, funding_msg.0, funding_msg.1)
1365 log_error!(self, "Got bad signatures: {}!", e.err);
1366 let mut channel_state = self.channel_state.lock().unwrap();
1367 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1368 node_id: chan.get_their_node_id(),
1375 // Because we have exclusive ownership of the channel here we can release the channel_state
1376 // lock before add_update_monitor
1377 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1381 let mut channel_state = self.channel_state.lock().unwrap();
1382 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1383 node_id: chan.get_their_node_id(),
1386 match channel_state.by_id.entry(chan.channel_id()) {
1387 hash_map::Entry::Occupied(_) => {
1388 panic!("Generated duplicate funding txid?");
1390 hash_map::Entry::Vacant(e) => {
1396 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1397 if !chan.should_announce() { return None }
1399 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1401 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1403 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1404 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1406 Some(msgs::AnnouncementSignatures {
1407 channel_id: chan.channel_id(),
1408 short_channel_id: chan.get_short_channel_id().unwrap(),
1409 node_signature: our_node_sig,
1410 bitcoin_signature: our_bitcoin_sig,
1414 /// Processes HTLCs which are pending waiting on random forward delay.
1416 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1417 /// Will likely generate further events.
1418 pub fn process_pending_htlc_forwards(&self) {
1419 let _ = self.total_consistency_lock.read().unwrap();
1421 let mut new_events = Vec::new();
1422 let mut failed_forwards = Vec::new();
1424 let mut channel_state_lock = self.channel_state.lock().unwrap();
1425 let channel_state = channel_state_lock.borrow_parts();
1427 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1431 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1432 if short_chan_id != 0 {
1433 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1434 Some(chan_id) => chan_id.clone(),
1436 failed_forwards.reserve(pending_forwards.len());
1437 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1438 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1439 short_channel_id: prev_short_channel_id,
1440 htlc_id: prev_htlc_id,
1441 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1443 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1448 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1450 let mut add_htlc_msgs = Vec::new();
1451 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1452 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1453 short_channel_id: prev_short_channel_id,
1454 htlc_id: prev_htlc_id,
1455 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1457 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()) {
1459 let chan_update = self.get_channel_update(forward_chan).unwrap();
1460 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1465 Some(msg) => { add_htlc_msgs.push(msg); },
1467 // Nothing to do here...we're waiting on a remote
1468 // revoke_and_ack before we can add anymore HTLCs. The Channel
1469 // will automatically handle building the update_add_htlc and
1470 // commitment_signed messages when we can.
1471 // TODO: Do some kind of timer to set the channel as !is_live()
1472 // as we don't really want others relying on us relaying through
1473 // this channel currently :/.
1480 if !add_htlc_msgs.is_empty() {
1481 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1484 if let ChannelError::Ignore(_) = e {
1485 panic!("Stated return value requirements in send_commitment() were not met");
1487 //TODO: Handle...this is bad!
1491 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1494 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1495 node_id: forward_chan.get_their_node_id(),
1496 updates: msgs::CommitmentUpdate {
1497 update_add_htlcs: add_htlc_msgs,
1498 update_fulfill_htlcs: Vec::new(),
1499 update_fail_htlcs: Vec::new(),
1500 update_fail_malformed_htlcs: Vec::new(),
1502 commitment_signed: commitment_msg,
1507 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1508 let prev_hop_data = HTLCPreviousHopData {
1509 short_channel_id: prev_short_channel_id,
1510 htlc_id: prev_htlc_id,
1511 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1513 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1514 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1515 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1517 new_events.push(events::Event::PaymentReceived {
1518 payment_hash: forward_info.payment_hash,
1519 amt: forward_info.amt_to_forward,
1526 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1528 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1529 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() }),
1533 if new_events.is_empty() { return }
1534 let mut events = self.pending_events.lock().unwrap();
1535 events.append(&mut new_events);
1538 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1539 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1540 let _ = self.total_consistency_lock.read().unwrap();
1542 let mut channel_state = Some(self.channel_state.lock().unwrap());
1543 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1544 if let Some(mut sources) = removed_source {
1545 for htlc_with_hash in sources.drain(..) {
1546 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1547 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() });
1553 /// Fails an HTLC backwards to the sender of it to us.
1554 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1555 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1556 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1557 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1558 /// still-available channels.
1559 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1561 HTLCSource::OutboundRoute { ref route, .. } => {
1562 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1563 mem::drop(channel_state_lock);
1564 match &onion_error {
1565 &HTLCFailReason::ErrorPacket { ref err } => {
1567 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1569 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1570 // TODO: If we decided to blame ourselves (or one of our channels) in
1571 // process_onion_failure we should close that channel as it implies our
1572 // next-hop is needlessly blaming us!
1573 if let Some(update) = channel_update {
1574 self.channel_state.lock().unwrap().pending_msg_events.push(
1575 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1580 self.pending_events.lock().unwrap().push(
1581 events::Event::PaymentFailed {
1582 payment_hash: payment_hash.clone(),
1583 rejected_by_dest: !payment_retryable,
1585 error_code: onion_error_code
1589 &HTLCFailReason::Reason {
1593 // we get a fail_malformed_htlc from the first hop
1594 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1595 // failures here, but that would be insufficient as Router::get_route
1596 // generally ignores its view of our own channels as we provide them via
1598 // TODO: For non-temporary failures, we really should be closing the
1599 // channel here as we apparently can't relay through them anyway.
1600 self.pending_events.lock().unwrap().push(
1601 events::Event::PaymentFailed {
1602 payment_hash: payment_hash.clone(),
1603 rejected_by_dest: route.hops.len() == 1,
1605 error_code: Some(*failure_code),
1611 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1612 let err_packet = match onion_error {
1613 HTLCFailReason::Reason { failure_code, data } => {
1614 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1615 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1616 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1618 HTLCFailReason::ErrorPacket { err } => {
1619 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1620 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1624 let channel_state = channel_state_lock.borrow_parts();
1626 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1627 Some(chan_id) => chan_id.clone(),
1631 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1632 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1633 Ok(Some((msg, commitment_msg, chan_monitor))) => {
1634 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1637 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1638 node_id: chan.get_their_node_id(),
1639 updates: msgs::CommitmentUpdate {
1640 update_add_htlcs: Vec::new(),
1641 update_fulfill_htlcs: Vec::new(),
1642 update_fail_htlcs: vec![msg],
1643 update_fail_malformed_htlcs: Vec::new(),
1645 commitment_signed: commitment_msg,
1651 //TODO: Do something with e?
1659 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1660 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1661 /// should probably kick the net layer to go send messages if this returns true!
1663 /// May panic if called except in response to a PaymentReceived event.
1664 pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1665 let mut sha = Sha256::new();
1666 sha.input(&payment_preimage.0[..]);
1667 let mut payment_hash = PaymentHash([0; 32]);
1668 sha.result(&mut payment_hash.0[..]);
1670 let _ = self.total_consistency_lock.read().unwrap();
1672 let mut channel_state = Some(self.channel_state.lock().unwrap());
1673 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1674 if let Some(mut sources) = removed_source {
1675 for htlc_with_hash in sources.drain(..) {
1676 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1677 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1682 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1684 HTLCSource::OutboundRoute { .. } => {
1685 mem::drop(channel_state_lock);
1686 let mut pending_events = self.pending_events.lock().unwrap();
1687 pending_events.push(events::Event::PaymentSent {
1691 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1692 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1693 let channel_state = channel_state_lock.borrow_parts();
1695 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1696 Some(chan_id) => chan_id.clone(),
1698 // TODO: There is probably a channel manager somewhere that needs to
1699 // learn the preimage as the channel already hit the chain and that's
1705 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1706 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1707 Ok((msgs, monitor_option)) => {
1708 if let Some(chan_monitor) = monitor_option {
1709 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1710 unimplemented!();// but def dont push the event...
1713 if let Some((msg, commitment_signed)) = msgs {
1714 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1715 node_id: chan.get_their_node_id(),
1716 updates: msgs::CommitmentUpdate {
1717 update_add_htlcs: Vec::new(),
1718 update_fulfill_htlcs: vec![msg],
1719 update_fail_htlcs: Vec::new(),
1720 update_fail_malformed_htlcs: Vec::new(),
1728 // TODO: There is probably a channel manager somewhere that needs to
1729 // learn the preimage as the channel may be about to hit the chain.
1730 //TODO: Do something with e?
1738 /// Gets the node_id held by this ChannelManager
1739 pub fn get_our_node_id(&self) -> PublicKey {
1740 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1743 /// Used to restore channels to normal operation after a
1744 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1746 pub fn test_restore_channel_monitor(&self) {
1747 let mut close_results = Vec::new();
1748 let mut htlc_forwards = Vec::new();
1749 let mut htlc_failures = Vec::new();
1750 let _ = self.total_consistency_lock.read().unwrap();
1753 let mut channel_lock = self.channel_state.lock().unwrap();
1754 let channel_state = channel_lock.borrow_parts();
1755 let short_to_id = channel_state.short_to_id;
1756 let pending_msg_events = channel_state.pending_msg_events;
1757 channel_state.by_id.retain(|_, channel| {
1758 if channel.is_awaiting_monitor_update() {
1759 let chan_monitor = channel.channel_monitor();
1760 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1762 ChannelMonitorUpdateErr::PermanentFailure => {
1763 // TODO: There may be some pending HTLCs that we intended to fail
1764 // backwards when a monitor update failed. We should make sure
1765 // knowledge of those gets moved into the appropriate in-memory
1766 // ChannelMonitor and they get failed backwards once we get
1767 // on-chain confirmations.
1768 // Note I think #198 addresses this, so once its merged a test
1769 // should be written.
1770 if let Some(short_id) = channel.get_short_channel_id() {
1771 short_to_id.remove(&short_id);
1773 close_results.push(channel.force_shutdown());
1774 if let Ok(update) = self.get_channel_update(&channel) {
1775 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1781 ChannelMonitorUpdateErr::TemporaryFailure => true,
1784 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1785 if !pending_forwards.is_empty() {
1786 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1788 htlc_failures.append(&mut pending_failures);
1790 macro_rules! handle_cs { () => {
1791 if let Some(update) = commitment_update {
1792 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1793 node_id: channel.get_their_node_id(),
1798 macro_rules! handle_raa { () => {
1799 if let Some(revoke_and_ack) = raa {
1800 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1801 node_id: channel.get_their_node_id(),
1802 msg: revoke_and_ack,
1807 RAACommitmentOrder::CommitmentFirst => {
1811 RAACommitmentOrder::RevokeAndACKFirst => {
1822 for failure in htlc_failures.drain(..) {
1823 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1825 self.forward_htlcs(&mut htlc_forwards[..]);
1827 for res in close_results.drain(..) {
1828 self.finish_force_close_channel(res);
1832 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1833 if msg.chain_hash != self.genesis_hash {
1834 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1837 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)
1838 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1839 let mut channel_state_lock = self.channel_state.lock().unwrap();
1840 let channel_state = channel_state_lock.borrow_parts();
1841 match channel_state.by_id.entry(channel.channel_id()) {
1842 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1843 hash_map::Entry::Vacant(entry) => {
1844 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1845 node_id: their_node_id.clone(),
1846 msg: channel.get_accept_channel(),
1848 entry.insert(channel);
1854 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1855 let (value, output_script, user_id) = {
1856 let mut channel_lock = self.channel_state.lock().unwrap();
1857 let channel_state = channel_lock.borrow_parts();
1858 match channel_state.by_id.entry(msg.temporary_channel_id) {
1859 hash_map::Entry::Occupied(mut chan) => {
1860 if chan.get().get_their_node_id() != *their_node_id {
1861 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1862 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1864 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1865 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1867 //TODO: same as above
1868 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1871 let mut pending_events = self.pending_events.lock().unwrap();
1872 pending_events.push(events::Event::FundingGenerationReady {
1873 temporary_channel_id: msg.temporary_channel_id,
1874 channel_value_satoshis: value,
1875 output_script: output_script,
1876 user_channel_id: user_id,
1881 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1882 let ((funding_msg, monitor_update), chan) = {
1883 let mut channel_lock = self.channel_state.lock().unwrap();
1884 let channel_state = channel_lock.borrow_parts();
1885 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1886 hash_map::Entry::Occupied(mut chan) => {
1887 if chan.get().get_their_node_id() != *their_node_id {
1888 //TODO: here and below MsgHandleErrInternal, #153 case
1889 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1891 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1893 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1896 // Because we have exclusive ownership of the channel here we can release the channel_state
1897 // lock before add_update_monitor
1898 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1901 let mut channel_state_lock = self.channel_state.lock().unwrap();
1902 let channel_state = channel_state_lock.borrow_parts();
1903 match channel_state.by_id.entry(funding_msg.channel_id) {
1904 hash_map::Entry::Occupied(_) => {
1905 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1907 hash_map::Entry::Vacant(e) => {
1908 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1909 node_id: their_node_id.clone(),
1918 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1919 let (funding_txo, user_id) = {
1920 let mut channel_lock = self.channel_state.lock().unwrap();
1921 let channel_state = channel_lock.borrow_parts();
1922 match channel_state.by_id.entry(msg.channel_id) {
1923 hash_map::Entry::Occupied(mut chan) => {
1924 if chan.get().get_their_node_id() != *their_node_id {
1925 //TODO: here and below MsgHandleErrInternal, #153 case
1926 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1928 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1929 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1932 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1934 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1937 let mut pending_events = self.pending_events.lock().unwrap();
1938 pending_events.push(events::Event::FundingBroadcastSafe {
1939 funding_txo: funding_txo,
1940 user_channel_id: user_id,
1945 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1946 let mut channel_state_lock = self.channel_state.lock().unwrap();
1947 let channel_state = channel_state_lock.borrow_parts();
1948 match channel_state.by_id.entry(msg.channel_id) {
1949 hash_map::Entry::Occupied(mut chan) => {
1950 if chan.get().get_their_node_id() != *their_node_id {
1951 //TODO: here and below MsgHandleErrInternal, #153 case
1952 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1954 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1955 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1956 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1957 node_id: their_node_id.clone(),
1958 msg: announcement_sigs,
1963 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1967 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1968 let (mut dropped_htlcs, chan_option) = {
1969 let mut channel_state_lock = self.channel_state.lock().unwrap();
1970 let channel_state = channel_state_lock.borrow_parts();
1972 match channel_state.by_id.entry(msg.channel_id.clone()) {
1973 hash_map::Entry::Occupied(mut chan_entry) => {
1974 if chan_entry.get().get_their_node_id() != *their_node_id {
1975 //TODO: here and below MsgHandleErrInternal, #153 case
1976 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1978 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1979 if let Some(msg) = shutdown {
1980 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1981 node_id: their_node_id.clone(),
1985 if let Some(msg) = closing_signed {
1986 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1987 node_id: their_node_id.clone(),
1991 if chan_entry.get().is_shutdown() {
1992 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1993 channel_state.short_to_id.remove(&short_id);
1995 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1996 } else { (dropped_htlcs, None) }
1998 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2001 for htlc_source in dropped_htlcs.drain(..) {
2002 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2004 if let Some(chan) = chan_option {
2005 if let Ok(update) = self.get_channel_update(&chan) {
2006 let mut channel_state = self.channel_state.lock().unwrap();
2007 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2015 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2016 let (tx, chan_option) = {
2017 let mut channel_state_lock = self.channel_state.lock().unwrap();
2018 let channel_state = channel_state_lock.borrow_parts();
2019 match channel_state.by_id.entry(msg.channel_id.clone()) {
2020 hash_map::Entry::Occupied(mut chan_entry) => {
2021 if chan_entry.get().get_their_node_id() != *their_node_id {
2022 //TODO: here and below MsgHandleErrInternal, #153 case
2023 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2025 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2026 if let Some(msg) = closing_signed {
2027 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2028 node_id: their_node_id.clone(),
2033 // We're done with this channel, we've got a signed closing transaction and
2034 // will send the closing_signed back to the remote peer upon return. This
2035 // also implies there are no pending HTLCs left on the channel, so we can
2036 // fully delete it from tracking (the channel monitor is still around to
2037 // watch for old state broadcasts)!
2038 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2039 channel_state.short_to_id.remove(&short_id);
2041 (tx, Some(chan_entry.remove_entry().1))
2042 } else { (tx, None) }
2044 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2047 if let Some(broadcast_tx) = tx {
2048 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2050 if let Some(chan) = chan_option {
2051 if let Ok(update) = self.get_channel_update(&chan) {
2052 let mut channel_state = self.channel_state.lock().unwrap();
2053 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2061 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2062 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2063 //determine the state of the payment based on our response/if we forward anything/the time
2064 //we take to respond. We should take care to avoid allowing such an attack.
2066 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2067 //us repeatedly garbled in different ways, and compare our error messages, which are
2068 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2069 //but we should prevent it anyway.
2071 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2072 let channel_state = channel_state_lock.borrow_parts();
2074 match channel_state.by_id.entry(msg.channel_id) {
2075 hash_map::Entry::Occupied(mut chan) => {
2076 if chan.get().get_their_node_id() != *their_node_id {
2077 //TODO: here MsgHandleErrInternal, #153 case
2078 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2080 if !chan.get().is_usable() {
2081 // If the update_add is completely bogus, the call will Err and we will close,
2082 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2083 // want to reject the new HTLC and fail it backwards instead of forwarding.
2084 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2085 let chan_update = self.get_channel_update(chan.get());
2086 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2087 channel_id: msg.channel_id,
2088 htlc_id: msg.htlc_id,
2089 reason: if let Ok(update) = chan_update {
2090 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2091 let mut res = Vec::with_capacity(8 + 128);
2092 res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2093 res.extend_from_slice(&update.encode_with_len()[..]);
2097 // This can only happen if the channel isn't in the fully-funded
2098 // state yet, implying our counterparty is trying to route payments
2099 // over the channel back to themselves (cause no one else should
2100 // know the short_id is a lightning channel yet). We should have no
2101 // problem just calling this unknown_next_peer
2102 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2107 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2109 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2114 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2115 let mut channel_lock = self.channel_state.lock().unwrap();
2117 let channel_state = channel_lock.borrow_parts();
2118 match channel_state.by_id.entry(msg.channel_id) {
2119 hash_map::Entry::Occupied(mut chan) => {
2120 if chan.get().get_their_node_id() != *their_node_id {
2121 //TODO: here and below MsgHandleErrInternal, #153 case
2122 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2124 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2126 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2129 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2133 // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2134 // indicating that the payment itself failed
2135 fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2136 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2139 let mut htlc_msat = *first_hop_htlc_msat;
2140 let mut error_code_ret = None;
2141 let mut next_route_hop_ix = 0;
2142 let mut is_from_final_node = false;
2144 // Handle packed channel/node updates for passing back for the route handler
2145 Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2146 next_route_hop_ix += 1;
2147 if res.is_some() { return; }
2149 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2150 htlc_msat = amt_to_forward;
2152 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2154 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2155 decryption_tmp.resize(packet_decrypted.len(), 0);
2156 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2157 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2158 packet_decrypted = decryption_tmp;
2160 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2162 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2163 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2164 let mut hmac = Hmac::new(Sha256::new(), &um);
2165 hmac.input(&err_packet.encode()[32..]);
2166 let mut calc_tag = [0u8; 32];
2167 hmac.raw_result(&mut calc_tag);
2169 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2170 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2171 const PERM: u16 = 0x4000;
2172 const NODE: u16 = 0x2000;
2173 const UPDATE: u16 = 0x1000;
2175 let error_code = byte_utils::slice_to_be16(&error_code_slice);
2176 error_code_ret = Some(error_code);
2178 let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2180 // indicate that payment parameter has failed and no need to
2181 // update Route object
2182 let payment_failed = (match error_code & 0xff {
2183 15|16|17|18|19 => true,
2185 } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2186 || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2188 let mut fail_channel_update = None;
2190 if error_code & NODE == NODE {
2191 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2193 else if error_code & PERM == PERM {
2194 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2195 short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2199 else if error_code & UPDATE == UPDATE {
2200 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2201 let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2202 if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2203 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2204 // if channel_update should NOT have caused the failure:
2205 // MAY treat the channel_update as invalid.
2206 let is_chan_update_invalid = match error_code & 0xff {
2208 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2210 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) });
2211 new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2213 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2214 14 => false, // expiry_too_soon; always valid?
2215 20 => chan_update.contents.flags & 2 == 0,
2216 _ => false, // unknown error code; take channel_update as valid
2218 fail_channel_update = if is_chan_update_invalid {
2219 // This probably indicates the node which forwarded
2220 // to the node in question corrupted something.
2221 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2222 short_channel_id: route_hop.short_channel_id,
2226 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2233 if fail_channel_update.is_none() {
2234 // They provided an UPDATE which was obviously bogus, not worth
2235 // trying to relay through them anymore.
2236 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2237 node_id: route_hop.pubkey,
2241 } else if !payment_failed {
2242 // We can't understand their error messages and they failed to
2243 // forward...they probably can't understand our forwards so its
2244 // really not worth trying any further.
2245 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2246 node_id: route_hop.pubkey,
2251 // TODO: Here (and a few other places) we assume that BADONION errors
2252 // are always "sourced" from the node previous to the one which failed
2253 // to decode the onion.
2254 res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2256 let (description, title) = errors::get_onion_error_description(error_code);
2257 if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2258 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2261 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2264 // Useless packet that we can't use but it passed HMAC, so it
2265 // definitely came from the peer in question
2266 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2267 node_id: route_hop.pubkey,
2269 }), !is_from_final_node));
2273 }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2274 if let Some((channel_update, payment_retryable)) = res {
2275 (channel_update, payment_retryable, error_code_ret)
2277 // only not set either packet unparseable or hmac does not match with any
2278 // payment not retryable only when garbage is from the final node
2279 (None, !is_from_final_node, None)
2281 } else { unreachable!(); }
2284 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2285 let mut channel_lock = self.channel_state.lock().unwrap();
2286 let channel_state = channel_lock.borrow_parts();
2287 match channel_state.by_id.entry(msg.channel_id) {
2288 hash_map::Entry::Occupied(mut chan) => {
2289 if chan.get().get_their_node_id() != *their_node_id {
2290 //TODO: here and below MsgHandleErrInternal, #153 case
2291 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2293 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2295 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2300 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2301 let mut channel_lock = self.channel_state.lock().unwrap();
2302 let channel_state = channel_lock.borrow_parts();
2303 match channel_state.by_id.entry(msg.channel_id) {
2304 hash_map::Entry::Occupied(mut chan) => {
2305 if chan.get().get_their_node_id() != *their_node_id {
2306 //TODO: here and below MsgHandleErrInternal, #153 case
2307 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2309 if (msg.failure_code & 0x8000) == 0 {
2310 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2312 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);
2315 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2319 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2320 let mut channel_state_lock = self.channel_state.lock().unwrap();
2321 let channel_state = channel_state_lock.borrow_parts();
2322 match channel_state.by_id.entry(msg.channel_id) {
2323 hash_map::Entry::Occupied(mut chan) => {
2324 if chan.get().get_their_node_id() != *their_node_id {
2325 //TODO: here and below MsgHandleErrInternal, #153 case
2326 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2328 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2329 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2330 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2331 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2332 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2334 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2335 node_id: their_node_id.clone(),
2336 msg: revoke_and_ack,
2338 if let Some(msg) = commitment_signed {
2339 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2340 node_id: their_node_id.clone(),
2341 updates: msgs::CommitmentUpdate {
2342 update_add_htlcs: Vec::new(),
2343 update_fulfill_htlcs: Vec::new(),
2344 update_fail_htlcs: Vec::new(),
2345 update_fail_malformed_htlcs: Vec::new(),
2347 commitment_signed: msg,
2351 if let Some(msg) = closing_signed {
2352 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2353 node_id: their_node_id.clone(),
2359 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2364 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2365 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2366 let mut forward_event = None;
2367 if !pending_forwards.is_empty() {
2368 let mut channel_state = self.channel_state.lock().unwrap();
2369 if channel_state.forward_htlcs.is_empty() {
2370 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));
2371 channel_state.next_forward = forward_event.unwrap();
2373 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2374 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2375 hash_map::Entry::Occupied(mut entry) => {
2376 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2378 hash_map::Entry::Vacant(entry) => {
2379 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2384 match forward_event {
2386 let mut pending_events = self.pending_events.lock().unwrap();
2387 pending_events.push(events::Event::PendingHTLCsForwardable {
2388 time_forwardable: time
2396 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2397 let (pending_forwards, mut pending_failures, short_channel_id) = {
2398 let mut channel_state_lock = self.channel_state.lock().unwrap();
2399 let channel_state = channel_state_lock.borrow_parts();
2400 match channel_state.by_id.entry(msg.channel_id) {
2401 hash_map::Entry::Occupied(mut chan) => {
2402 if chan.get().get_their_node_id() != *their_node_id {
2403 //TODO: here and below MsgHandleErrInternal, #153 case
2404 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2406 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2407 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2408 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2409 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2411 if let Some(updates) = commitment_update {
2412 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2413 node_id: their_node_id.clone(),
2417 if let Some(msg) = closing_signed {
2418 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2419 node_id: their_node_id.clone(),
2423 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2425 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2428 for failure in pending_failures.drain(..) {
2429 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2431 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2436 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2437 let mut channel_lock = self.channel_state.lock().unwrap();
2438 let channel_state = channel_lock.borrow_parts();
2439 match channel_state.by_id.entry(msg.channel_id) {
2440 hash_map::Entry::Occupied(mut chan) => {
2441 if chan.get().get_their_node_id() != *their_node_id {
2442 //TODO: here and below MsgHandleErrInternal, #153 case
2443 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2445 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2447 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2452 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2453 let mut channel_state_lock = self.channel_state.lock().unwrap();
2454 let channel_state = channel_state_lock.borrow_parts();
2456 match channel_state.by_id.entry(msg.channel_id) {
2457 hash_map::Entry::Occupied(mut chan) => {
2458 if chan.get().get_their_node_id() != *their_node_id {
2459 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2461 if !chan.get().is_usable() {
2462 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2465 let our_node_id = self.get_our_node_id();
2466 let (announcement, our_bitcoin_sig) =
2467 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2469 let were_node_one = announcement.node_id_1 == our_node_id;
2470 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2471 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2472 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2473 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2476 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2478 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2479 msg: msgs::ChannelAnnouncement {
2480 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2481 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2482 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2483 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2484 contents: announcement,
2486 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2489 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2494 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2495 let mut channel_state_lock = self.channel_state.lock().unwrap();
2496 let channel_state = channel_state_lock.borrow_parts();
2498 match channel_state.by_id.entry(msg.channel_id) {
2499 hash_map::Entry::Occupied(mut chan) => {
2500 if chan.get().get_their_node_id() != *their_node_id {
2501 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2503 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2504 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2505 if let Some(monitor) = channel_monitor {
2506 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2507 // channel_reestablish doesn't guarantee the order it returns is sensical
2508 // for the messages it returns, but if we're setting what messages to
2509 // re-transmit on monitor update success, we need to make sure it is sane.
2510 if revoke_and_ack.is_none() {
2511 order = RAACommitmentOrder::CommitmentFirst;
2513 if commitment_update.is_none() {
2514 order = RAACommitmentOrder::RevokeAndACKFirst;
2516 return_monitor_err!(self, e, channel_state, chan, order);
2517 //TODO: Resend the funding_locked if needed once we get the monitor running again
2520 if let Some(msg) = funding_locked {
2521 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2522 node_id: their_node_id.clone(),
2526 macro_rules! send_raa { () => {
2527 if let Some(msg) = revoke_and_ack {
2528 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2529 node_id: their_node_id.clone(),
2534 macro_rules! send_cu { () => {
2535 if let Some(updates) = commitment_update {
2536 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2537 node_id: their_node_id.clone(),
2543 RAACommitmentOrder::RevokeAndACKFirst => {
2547 RAACommitmentOrder::CommitmentFirst => {
2552 if let Some(msg) = shutdown {
2553 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2554 node_id: their_node_id.clone(),
2560 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2564 /// Begin Update fee process. Allowed only on an outbound channel.
2565 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2566 /// PeerManager::process_events afterwards.
2567 /// Note: This API is likely to change!
2569 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2570 let _ = self.total_consistency_lock.read().unwrap();
2572 let err: Result<(), _> = loop {
2573 let mut channel_state_lock = self.channel_state.lock().unwrap();
2574 let channel_state = channel_state_lock.borrow_parts();
2576 match channel_state.by_id.entry(channel_id) {
2577 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2578 hash_map::Entry::Occupied(mut chan) => {
2579 if !chan.get().is_outbound() {
2580 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2582 if chan.get().is_awaiting_monitor_update() {
2583 return Err(APIError::MonitorUpdateFailed);
2585 if !chan.get().is_live() {
2586 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2588 their_node_id = chan.get().get_their_node_id();
2589 if let Some((update_fee, commitment_signed, chan_monitor)) =
2590 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2592 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2595 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2596 node_id: chan.get().get_their_node_id(),
2597 updates: msgs::CommitmentUpdate {
2598 update_add_htlcs: Vec::new(),
2599 update_fulfill_htlcs: Vec::new(),
2600 update_fail_htlcs: Vec::new(),
2601 update_fail_malformed_htlcs: Vec::new(),
2602 update_fee: Some(update_fee),
2612 match handle_error!(self, err, their_node_id) {
2613 Ok(_) => unreachable!(),
2615 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2617 log_error!(self, "Got bad keys: {}!", e.err);
2618 let mut channel_state = self.channel_state.lock().unwrap();
2619 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2620 node_id: their_node_id,
2624 Err(APIError::APIMisuseError { err: e.err })
2630 impl events::MessageSendEventsProvider for ChannelManager {
2631 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2632 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2633 // user to serialize a ChannelManager with pending events in it and lose those events on
2634 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2636 //TODO: This behavior should be documented.
2637 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2638 if let Some(preimage) = htlc_update.payment_preimage {
2639 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2640 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2642 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2643 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2648 let mut ret = Vec::new();
2649 let mut channel_state = self.channel_state.lock().unwrap();
2650 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2655 impl events::EventsProvider for ChannelManager {
2656 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2657 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2658 // user to serialize a ChannelManager with pending events in it and lose those events on
2659 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2661 //TODO: This behavior should be documented.
2662 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2663 if let Some(preimage) = htlc_update.payment_preimage {
2664 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2665 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2667 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2668 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2673 let mut ret = Vec::new();
2674 let mut pending_events = self.pending_events.lock().unwrap();
2675 mem::swap(&mut ret, &mut *pending_events);
2680 impl ChainListener for ChannelManager {
2681 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2682 let header_hash = header.bitcoin_hash();
2683 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
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 log_trace!(self, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
2717 if let Some(short_id) = channel.get_short_channel_id() {
2718 short_to_id.remove(&short_id);
2720 // It looks like our counterparty went on-chain. We go ahead and
2721 // broadcast our latest local state as well here, just in case its
2722 // some kind of SPV attack, though we expect these to be dropped.
2723 failed_channels.push(channel.force_shutdown());
2724 if let Ok(update) = self.get_channel_update(&channel) {
2725 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2734 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2735 if let Some(short_id) = channel.get_short_channel_id() {
2736 short_to_id.remove(&short_id);
2738 failed_channels.push(channel.force_shutdown());
2739 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2740 // the latest local tx for us, so we should skip that here (it doesn't really
2741 // hurt anything, but does make tests a bit simpler).
2742 failed_channels.last_mut().unwrap().0 = Vec::new();
2743 if let Ok(update) = self.get_channel_update(&channel) {
2744 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2753 for failure in failed_channels.drain(..) {
2754 self.finish_force_close_channel(failure);
2756 self.latest_block_height.store(height as usize, Ordering::Release);
2757 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2760 /// We force-close the channel without letting our counterparty participate in the shutdown
2761 fn block_disconnected(&self, header: &BlockHeader) {
2762 let _ = self.total_consistency_lock.read().unwrap();
2763 let mut failed_channels = Vec::new();
2765 let mut channel_lock = self.channel_state.lock().unwrap();
2766 let channel_state = channel_lock.borrow_parts();
2767 let short_to_id = channel_state.short_to_id;
2768 let pending_msg_events = channel_state.pending_msg_events;
2769 channel_state.by_id.retain(|_, v| {
2770 if v.block_disconnected(header) {
2771 if let Some(short_id) = v.get_short_channel_id() {
2772 short_to_id.remove(&short_id);
2774 failed_channels.push(v.force_shutdown());
2775 if let Ok(update) = self.get_channel_update(&v) {
2776 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2786 for failure in failed_channels.drain(..) {
2787 self.finish_force_close_channel(failure);
2789 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2790 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2794 impl ChannelMessageHandler for ChannelManager {
2795 //TODO: Handle errors and close channel (or so)
2796 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2797 let _ = self.total_consistency_lock.read().unwrap();
2798 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2801 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2802 let _ = self.total_consistency_lock.read().unwrap();
2803 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2806 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2807 let _ = self.total_consistency_lock.read().unwrap();
2808 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2811 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2812 let _ = self.total_consistency_lock.read().unwrap();
2813 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2816 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2817 let _ = self.total_consistency_lock.read().unwrap();
2818 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2821 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2822 let _ = self.total_consistency_lock.read().unwrap();
2823 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2826 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2827 let _ = self.total_consistency_lock.read().unwrap();
2828 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2831 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2832 let _ = self.total_consistency_lock.read().unwrap();
2833 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2836 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2837 let _ = self.total_consistency_lock.read().unwrap();
2838 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2841 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2842 let _ = self.total_consistency_lock.read().unwrap();
2843 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2846 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2847 let _ = self.total_consistency_lock.read().unwrap();
2848 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2851 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2852 let _ = self.total_consistency_lock.read().unwrap();
2853 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2856 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2857 let _ = self.total_consistency_lock.read().unwrap();
2858 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2861 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2862 let _ = self.total_consistency_lock.read().unwrap();
2863 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2866 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2867 let _ = self.total_consistency_lock.read().unwrap();
2868 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2871 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2872 let _ = self.total_consistency_lock.read().unwrap();
2873 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2876 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2877 let _ = self.total_consistency_lock.read().unwrap();
2878 let mut failed_channels = Vec::new();
2879 let mut failed_payments = Vec::new();
2881 let mut channel_state_lock = self.channel_state.lock().unwrap();
2882 let channel_state = channel_state_lock.borrow_parts();
2883 let short_to_id = channel_state.short_to_id;
2884 let pending_msg_events = channel_state.pending_msg_events;
2885 if no_connection_possible {
2886 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2887 channel_state.by_id.retain(|_, chan| {
2888 if chan.get_their_node_id() == *their_node_id {
2889 if let Some(short_id) = chan.get_short_channel_id() {
2890 short_to_id.remove(&short_id);
2892 failed_channels.push(chan.force_shutdown());
2893 if let Ok(update) = self.get_channel_update(&chan) {
2894 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2904 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2905 channel_state.by_id.retain(|_, chan| {
2906 if chan.get_their_node_id() == *their_node_id {
2907 //TODO: mark channel disabled (and maybe announce such after a timeout).
2908 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2909 if !failed_adds.is_empty() {
2910 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
2911 failed_payments.push((chan_update, failed_adds));
2913 if chan.is_shutdown() {
2914 if let Some(short_id) = chan.get_short_channel_id() {
2915 short_to_id.remove(&short_id);
2924 for failure in failed_channels.drain(..) {
2925 self.finish_force_close_channel(failure);
2927 for (chan_update, mut htlc_sources) in failed_payments {
2928 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2929 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2934 fn peer_connected(&self, their_node_id: &PublicKey) {
2935 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2937 let _ = self.total_consistency_lock.read().unwrap();
2938 let mut channel_state_lock = self.channel_state.lock().unwrap();
2939 let channel_state = channel_state_lock.borrow_parts();
2940 let pending_msg_events = channel_state.pending_msg_events;
2941 channel_state.by_id.retain(|_, chan| {
2942 if chan.get_their_node_id() == *their_node_id {
2943 if !chan.have_received_message() {
2944 // If we created this (outbound) channel while we were disconnected from the
2945 // peer we probably failed to send the open_channel message, which is now
2946 // lost. We can't have had anything pending related to this channel, so we just
2950 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2951 node_id: chan.get_their_node_id(),
2952 msg: chan.get_channel_reestablish(),
2958 //TODO: Also re-broadcast announcement_signatures
2961 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2962 let _ = self.total_consistency_lock.read().unwrap();
2964 if msg.channel_id == [0; 32] {
2965 for chan in self.list_channels() {
2966 if chan.remote_network_id == *their_node_id {
2967 self.force_close_channel(&chan.channel_id);
2971 self.force_close_channel(&msg.channel_id);
2976 const SERIALIZATION_VERSION: u8 = 1;
2977 const MIN_SERIALIZATION_VERSION: u8 = 1;
2979 impl Writeable for PendingForwardHTLCInfo {
2980 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2981 if let &Some(ref onion) = &self.onion_packet {
2983 onion.write(writer)?;
2987 self.incoming_shared_secret.write(writer)?;
2988 self.payment_hash.write(writer)?;
2989 self.short_channel_id.write(writer)?;
2990 self.amt_to_forward.write(writer)?;
2991 self.outgoing_cltv_value.write(writer)?;
2996 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2997 fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2998 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
3000 1 => Some(msgs::OnionPacket::read(reader)?),
3001 _ => return Err(DecodeError::InvalidValue),
3003 Ok(PendingForwardHTLCInfo {
3005 incoming_shared_secret: Readable::read(reader)?,
3006 payment_hash: Readable::read(reader)?,
3007 short_channel_id: Readable::read(reader)?,
3008 amt_to_forward: Readable::read(reader)?,
3009 outgoing_cltv_value: Readable::read(reader)?,
3014 impl Writeable for HTLCFailureMsg {
3015 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3017 &HTLCFailureMsg::Relay(ref fail_msg) => {
3019 fail_msg.write(writer)?;
3021 &HTLCFailureMsg::Malformed(ref fail_msg) => {
3023 fail_msg.write(writer)?;
3030 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3031 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3032 match <u8 as Readable<R>>::read(reader)? {
3033 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3034 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3035 _ => Err(DecodeError::InvalidValue),
3040 impl Writeable for PendingHTLCStatus {
3041 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3043 &PendingHTLCStatus::Forward(ref forward_info) => {
3045 forward_info.write(writer)?;
3047 &PendingHTLCStatus::Fail(ref fail_msg) => {
3049 fail_msg.write(writer)?;
3056 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3057 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3058 match <u8 as Readable<R>>::read(reader)? {
3059 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3060 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3061 _ => Err(DecodeError::InvalidValue),
3066 impl_writeable!(HTLCPreviousHopData, 0, {
3069 incoming_packet_shared_secret
3072 impl Writeable for HTLCSource {
3073 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3075 &HTLCSource::PreviousHopData(ref hop_data) => {
3077 hop_data.write(writer)?;
3079 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3081 route.write(writer)?;
3082 session_priv.write(writer)?;
3083 first_hop_htlc_msat.write(writer)?;
3090 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3091 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3092 match <u8 as Readable<R>>::read(reader)? {
3093 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3094 1 => Ok(HTLCSource::OutboundRoute {
3095 route: Readable::read(reader)?,
3096 session_priv: Readable::read(reader)?,
3097 first_hop_htlc_msat: Readable::read(reader)?,
3099 _ => Err(DecodeError::InvalidValue),
3104 impl Writeable for HTLCFailReason {
3105 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3107 &HTLCFailReason::ErrorPacket { ref err } => {
3111 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3113 failure_code.write(writer)?;
3114 data.write(writer)?;
3121 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3122 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3123 match <u8 as Readable<R>>::read(reader)? {
3124 0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3125 1 => Ok(HTLCFailReason::Reason {
3126 failure_code: Readable::read(reader)?,
3127 data: Readable::read(reader)?,
3129 _ => Err(DecodeError::InvalidValue),
3134 impl_writeable!(HTLCForwardInfo, 0, {
3135 prev_short_channel_id,
3140 impl Writeable for ChannelManager {
3141 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3142 let _ = self.total_consistency_lock.write().unwrap();
3144 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3145 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3147 self.genesis_hash.write(writer)?;
3148 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3149 self.last_block_hash.lock().unwrap().write(writer)?;
3151 let channel_state = self.channel_state.lock().unwrap();
3152 let mut unfunded_channels = 0;
3153 for (_, channel) in channel_state.by_id.iter() {
3154 if !channel.is_funding_initiated() {
3155 unfunded_channels += 1;
3158 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3159 for (_, channel) in channel_state.by_id.iter() {
3160 if channel.is_funding_initiated() {
3161 channel.write(writer)?;
3165 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3166 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3167 short_channel_id.write(writer)?;
3168 (pending_forwards.len() as u64).write(writer)?;
3169 for forward in pending_forwards {
3170 forward.write(writer)?;
3174 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3175 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3176 payment_hash.write(writer)?;
3177 (previous_hops.len() as u64).write(writer)?;
3178 for previous_hop in previous_hops {
3179 previous_hop.write(writer)?;
3187 /// Arguments for the creation of a ChannelManager that are not deserialized.
3189 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3191 /// 1) Deserialize all stored ChannelMonitors.
3192 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3193 /// ChannelManager)>::read(reader, args).
3194 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3195 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3196 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3197 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3198 /// 4) Reconnect blocks on your ChannelMonitors.
3199 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3200 /// 6) Disconnect/connect blocks on the ChannelManager.
3201 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3202 /// automatically as it does in ChannelManager::new()).
3203 pub struct ChannelManagerReadArgs<'a> {
3204 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3205 /// deserialization.
3206 pub keys_manager: Arc<KeysInterface>,
3208 /// The fee_estimator for use in the ChannelManager in the future.
3210 /// No calls to the FeeEstimator will be made during deserialization.
3211 pub fee_estimator: Arc<FeeEstimator>,
3212 /// The ManyChannelMonitor for use in the ChannelManager in the future.
3214 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3215 /// you have deserialized ChannelMonitors separately and will add them to your
3216 /// ManyChannelMonitor after deserializing this ChannelManager.
3217 pub monitor: Arc<ManyChannelMonitor>,
3218 /// The ChainWatchInterface for use in the ChannelManager in the future.
3220 /// No calls to the ChainWatchInterface will be made during deserialization.
3221 pub chain_monitor: Arc<ChainWatchInterface>,
3222 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3223 /// used to broadcast the latest local commitment transactions of channels which must be
3224 /// force-closed during deserialization.
3225 pub tx_broadcaster: Arc<BroadcasterInterface>,
3226 /// The Logger for use in the ChannelManager and which may be used to log information during
3227 /// deserialization.
3228 pub logger: Arc<Logger>,
3229 /// Default settings used for new channels. Any existing channels will continue to use the
3230 /// runtime settings which were stored when the ChannelManager was serialized.
3231 pub default_config: UserConfig,
3233 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3234 /// value.get_funding_txo() should be the key).
3236 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3237 /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3238 /// is true for missing channels as well. If there is a monitor missing for which we find
3239 /// channel data Err(DecodeError::InvalidValue) will be returned.
3241 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3243 pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3246 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3247 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3248 let _ver: u8 = Readable::read(reader)?;
3249 let min_ver: u8 = Readable::read(reader)?;
3250 if min_ver > SERIALIZATION_VERSION {
3251 return Err(DecodeError::UnknownVersion);
3254 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3255 let latest_block_height: u32 = Readable::read(reader)?;
3256 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3258 let mut closed_channels = Vec::new();
3260 let channel_count: u64 = Readable::read(reader)?;
3261 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3262 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3263 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3264 for _ in 0..channel_count {
3265 let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3266 if channel.last_block_connected != last_block_hash {
3267 return Err(DecodeError::InvalidValue);
3270 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3271 funding_txo_set.insert(funding_txo.clone());
3272 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3273 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3274 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3275 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3276 let mut force_close_res = channel.force_shutdown();
3277 force_close_res.0 = monitor.get_latest_local_commitment_txn();
3278 closed_channels.push(force_close_res);
3280 if let Some(short_channel_id) = channel.get_short_channel_id() {
3281 short_to_id.insert(short_channel_id, channel.channel_id());
3283 by_id.insert(channel.channel_id(), channel);
3286 return Err(DecodeError::InvalidValue);
3290 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3291 if !funding_txo_set.contains(funding_txo) {
3292 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3296 let forward_htlcs_count: u64 = Readable::read(reader)?;
3297 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3298 for _ in 0..forward_htlcs_count {
3299 let short_channel_id = Readable::read(reader)?;
3300 let pending_forwards_count: u64 = Readable::read(reader)?;
3301 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3302 for _ in 0..pending_forwards_count {
3303 pending_forwards.push(Readable::read(reader)?);
3305 forward_htlcs.insert(short_channel_id, pending_forwards);
3308 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3309 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3310 for _ in 0..claimable_htlcs_count {
3311 let payment_hash = Readable::read(reader)?;
3312 let previous_hops_len: u64 = Readable::read(reader)?;
3313 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3314 for _ in 0..previous_hops_len {
3315 previous_hops.push(Readable::read(reader)?);
3317 claimable_htlcs.insert(payment_hash, previous_hops);
3320 let channel_manager = ChannelManager {
3322 fee_estimator: args.fee_estimator,
3323 monitor: args.monitor,
3324 chain_monitor: args.chain_monitor,
3325 tx_broadcaster: args.tx_broadcaster,
3327 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3328 last_block_hash: Mutex::new(last_block_hash),
3329 secp_ctx: Secp256k1::new(),
3331 channel_state: Mutex::new(ChannelHolder {
3334 next_forward: Instant::now(),
3337 pending_msg_events: Vec::new(),
3339 our_network_key: args.keys_manager.get_node_secret(),
3341 pending_events: Mutex::new(Vec::new()),
3342 total_consistency_lock: RwLock::new(()),
3343 keys_manager: args.keys_manager,
3344 logger: args.logger,
3345 default_configuration: args.default_config,
3348 for close_res in closed_channels.drain(..) {
3349 channel_manager.finish_force_close_channel(close_res);
3350 //TODO: Broadcast channel update for closed channels, but only after we've made a
3351 //connection or two.
3354 Ok((last_block_hash.clone(), channel_manager))
3360 use chain::chaininterface;
3361 use chain::transaction::OutPoint;
3362 use chain::chaininterface::{ChainListener, ChainWatchInterface};
3363 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3364 use chain::keysinterface;
3365 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3366 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3367 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3368 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3369 use ln::router::{Route, RouteHop, Router};
3371 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3372 use util::test_utils;
3373 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3374 use util::errors::APIError;
3375 use util::logger::Logger;
3376 use util::ser::{Writeable, Writer, ReadableArgs};
3377 use util::config::UserConfig;
3379 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3380 use bitcoin::util::bip143;
3381 use bitcoin::util::address::Address;
3382 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3383 use bitcoin::blockdata::block::{Block, BlockHeader};
3384 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3385 use bitcoin::blockdata::script::{Builder, Script};
3386 use bitcoin::blockdata::opcodes;
3387 use bitcoin::blockdata::constants::genesis_block;
3388 use bitcoin::network::constants::Network;
3392 use secp256k1::{Secp256k1, Message};
3393 use secp256k1::key::{PublicKey,SecretKey};
3395 use crypto::sha2::Sha256;
3396 use crypto::digest::Digest;
3398 use rand::{thread_rng,Rng};
3400 use std::cell::RefCell;
3401 use std::collections::{BTreeSet, HashMap, HashSet};
3402 use std::default::Default;
3404 use std::sync::{Arc, Mutex};
3405 use std::sync::atomic::Ordering;
3406 use std::time::Instant;
3409 fn build_test_onion_keys() -> Vec<OnionKeys> {
3410 // Keys from BOLT 4, used in both test vector tests
3411 let secp_ctx = Secp256k1::new();
3416 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3417 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
3420 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3421 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
3424 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3425 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
3428 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3429 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
3432 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3433 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
3438 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3440 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3441 assert_eq!(onion_keys.len(), route.hops.len());
3446 fn onion_vectors() {
3447 // Packet creation test vectors from BOLT 4
3448 let onion_keys = build_test_onion_keys();
3450 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3451 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3452 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3453 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3454 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3456 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3457 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3458 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3459 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3460 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3462 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3463 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3464 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3465 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3466 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3468 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3469 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3470 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3471 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3472 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3474 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3475 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3476 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3477 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3478 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3480 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3481 let payloads = vec!(
3482 msgs::OnionHopData {
3484 data: msgs::OnionRealm0HopData {
3485 short_channel_id: 0,
3487 outgoing_cltv_value: 0,
3491 msgs::OnionHopData {
3493 data: msgs::OnionRealm0HopData {
3494 short_channel_id: 0x0101010101010101,
3495 amt_to_forward: 0x0100000001,
3496 outgoing_cltv_value: 0,
3500 msgs::OnionHopData {
3502 data: msgs::OnionRealm0HopData {
3503 short_channel_id: 0x0202020202020202,
3504 amt_to_forward: 0x0200000002,
3505 outgoing_cltv_value: 0,
3509 msgs::OnionHopData {
3511 data: msgs::OnionRealm0HopData {
3512 short_channel_id: 0x0303030303030303,
3513 amt_to_forward: 0x0300000003,
3514 outgoing_cltv_value: 0,
3518 msgs::OnionHopData {
3520 data: msgs::OnionRealm0HopData {
3521 short_channel_id: 0x0404040404040404,
3522 amt_to_forward: 0x0400000004,
3523 outgoing_cltv_value: 0,
3529 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3530 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3532 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3536 fn test_failure_packet_onion() {
3537 // Returning Errors test vectors from BOLT 4
3539 let onion_keys = build_test_onion_keys();
3540 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3541 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3543 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3544 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3546 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3547 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3549 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3550 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3552 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3553 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3555 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3556 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3559 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3560 assert!(chain.does_match_tx(tx));
3561 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3562 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3564 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3565 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3570 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3571 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3572 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3573 node: Arc<ChannelManager>,
3575 node_seed: [u8; 32],
3576 network_payment_count: Rc<RefCell<u8>>,
3577 network_chan_count: Rc<RefCell<u32>>,
3579 impl Drop for Node {
3580 fn drop(&mut self) {
3581 if !::std::thread::panicking() {
3582 // Check that we processed all pending events
3583 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3584 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3585 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3590 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3591 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3594 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) {
3595 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3596 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3597 (announcement, as_update, bs_update, channel_id, tx)
3600 macro_rules! get_revoke_commit_msgs {
3601 ($node: expr, $node_id: expr) => {
3603 let events = $node.node.get_and_clear_pending_msg_events();
3604 assert_eq!(events.len(), 2);
3606 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3607 assert_eq!(*node_id, $node_id);
3610 _ => panic!("Unexpected event"),
3611 }, match events[1] {
3612 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3613 assert_eq!(*node_id, $node_id);
3614 assert!(updates.update_add_htlcs.is_empty());
3615 assert!(updates.update_fulfill_htlcs.is_empty());
3616 assert!(updates.update_fail_htlcs.is_empty());
3617 assert!(updates.update_fail_malformed_htlcs.is_empty());
3618 assert!(updates.update_fee.is_none());
3619 updates.commitment_signed.clone()
3621 _ => panic!("Unexpected event"),
3627 macro_rules! get_event_msg {
3628 ($node: expr, $event_type: path, $node_id: expr) => {
3630 let events = $node.node.get_and_clear_pending_msg_events();
3631 assert_eq!(events.len(), 1);
3633 $event_type { ref node_id, ref msg } => {
3634 assert_eq!(*node_id, $node_id);
3637 _ => panic!("Unexpected event"),
3643 macro_rules! get_htlc_update_msgs {
3644 ($node: expr, $node_id: expr) => {
3646 let events = $node.node.get_and_clear_pending_msg_events();
3647 assert_eq!(events.len(), 1);
3649 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3650 assert_eq!(*node_id, $node_id);
3653 _ => panic!("Unexpected event"),
3659 macro_rules! get_feerate {
3660 ($node: expr, $channel_id: expr) => {
3662 let chan_lock = $node.node.channel_state.lock().unwrap();
3663 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3670 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3671 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3672 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();
3673 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();
3675 let chan_id = *node_a.network_chan_count.borrow();
3679 let events_2 = node_a.node.get_and_clear_pending_events();
3680 assert_eq!(events_2.len(), 1);
3682 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3683 assert_eq!(*channel_value_satoshis, channel_value);
3684 assert_eq!(user_channel_id, 42);
3686 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3687 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3689 funding_output = OutPoint::new(tx.txid(), 0);
3691 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3692 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3693 assert_eq!(added_monitors.len(), 1);
3694 assert_eq!(added_monitors[0].0, funding_output);
3695 added_monitors.clear();
3697 _ => panic!("Unexpected event"),
3700 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();
3702 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3703 assert_eq!(added_monitors.len(), 1);
3704 assert_eq!(added_monitors[0].0, funding_output);
3705 added_monitors.clear();
3708 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();
3710 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3711 assert_eq!(added_monitors.len(), 1);
3712 assert_eq!(added_monitors[0].0, funding_output);
3713 added_monitors.clear();
3716 let events_4 = node_a.node.get_and_clear_pending_events();
3717 assert_eq!(events_4.len(), 1);
3719 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3720 assert_eq!(user_channel_id, 42);
3721 assert_eq!(*funding_txo, funding_output);
3723 _ => panic!("Unexpected event"),
3729 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3730 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3731 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();
3735 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3736 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3737 assert_eq!(events_6.len(), 2);
3738 ((match events_6[0] {
3739 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3740 channel_id = msg.channel_id.clone();
3741 assert_eq!(*node_id, node_b.node.get_our_node_id());
3744 _ => panic!("Unexpected event"),
3745 }, match events_6[1] {
3746 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3747 assert_eq!(*node_id, node_b.node.get_our_node_id());
3750 _ => panic!("Unexpected event"),
3754 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) {
3755 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3756 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3760 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) {
3761 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3762 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3763 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3765 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3766 assert_eq!(events_7.len(), 1);
3767 let (announcement, bs_update) = match events_7[0] {
3768 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3771 _ => panic!("Unexpected event"),
3774 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3775 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3776 assert_eq!(events_8.len(), 1);
3777 let as_update = match events_8[0] {
3778 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3779 assert!(*announcement == *msg);
3782 _ => panic!("Unexpected event"),
3785 *node_a.network_chan_count.borrow_mut() += 1;
3787 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3790 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3791 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3794 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) {
3795 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3797 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3798 node.router.handle_channel_update(&chan_announcement.1).unwrap();
3799 node.router.handle_channel_update(&chan_announcement.2).unwrap();
3801 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3804 macro_rules! check_spends {
3805 ($tx: expr, $spends_tx: expr) => {
3807 let mut funding_tx_map = HashMap::new();
3808 let spends_tx = $spends_tx;
3809 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3810 $tx.verify(&funding_tx_map).unwrap();
3815 macro_rules! get_closing_signed_broadcast {
3816 ($node: expr, $dest_pubkey: expr) => {
3818 let events = $node.get_and_clear_pending_msg_events();
3819 assert!(events.len() == 1 || events.len() == 2);
3820 (match events[events.len() - 1] {
3821 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3822 assert_eq!(msg.contents.flags & 2, 2);
3825 _ => panic!("Unexpected event"),
3826 }, if events.len() == 2 {
3828 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3829 assert_eq!(*node_id, $dest_pubkey);
3832 _ => panic!("Unexpected event"),
3839 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) {
3840 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) };
3841 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3844 node_a.close_channel(channel_id).unwrap();
3845 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3847 let events_1 = node_b.get_and_clear_pending_msg_events();
3848 assert!(events_1.len() >= 1);
3849 let shutdown_b = match events_1[0] {
3850 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3851 assert_eq!(node_id, &node_a.get_our_node_id());
3854 _ => panic!("Unexpected event"),
3857 let closing_signed_b = if !close_inbound_first {
3858 assert_eq!(events_1.len(), 1);
3861 Some(match events_1[1] {
3862 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3863 assert_eq!(node_id, &node_a.get_our_node_id());
3866 _ => panic!("Unexpected event"),
3870 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3871 let (as_update, bs_update) = if close_inbound_first {
3872 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3873 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3874 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3875 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3876 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3878 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3879 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3880 assert!(none_b.is_none());
3881 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3882 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3883 (as_update, bs_update)
3885 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3887 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3888 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3889 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3890 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3892 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3893 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3894 assert!(none_a.is_none());
3895 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3896 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3897 (as_update, bs_update)
3899 assert_eq!(tx_a, tx_b);
3900 check_spends!(tx_a, funding_tx);
3902 (as_update, bs_update, tx_a)
3907 msgs: Vec<msgs::UpdateAddHTLC>,
3908 commitment_msg: msgs::CommitmentSigned,
3911 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3912 assert!(updates.update_fulfill_htlcs.is_empty());
3913 assert!(updates.update_fail_htlcs.is_empty());
3914 assert!(updates.update_fail_malformed_htlcs.is_empty());
3915 assert!(updates.update_fee.is_none());
3916 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3919 fn from_event(event: MessageSendEvent) -> SendEvent {
3921 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3922 _ => panic!("Unexpected event type!"),
3926 fn from_node(node: &Node) -> SendEvent {
3927 let mut events = node.node.get_and_clear_pending_msg_events();
3928 assert_eq!(events.len(), 1);
3929 SendEvent::from_event(events.pop().unwrap())
3933 macro_rules! check_added_monitors {
3934 ($node: expr, $count: expr) => {
3936 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3937 assert_eq!(added_monitors.len(), $count);
3938 added_monitors.clear();
3943 macro_rules! commitment_signed_dance {
3944 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3946 check_added_monitors!($node_a, 0);
3947 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3948 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3949 check_added_monitors!($node_a, 1);
3950 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3953 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3955 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3956 check_added_monitors!($node_b, 0);
3957 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3958 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3959 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3960 check_added_monitors!($node_b, 1);
3961 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3962 let (bs_revoke_and_ack, extra_msg_option) = {
3963 let events = $node_b.node.get_and_clear_pending_msg_events();
3964 assert!(events.len() <= 2);
3966 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3967 assert_eq!(*node_id, $node_a.node.get_our_node_id());
3970 _ => panic!("Unexpected event"),
3971 }, events.get(1).map(|e| e.clone()))
3973 check_added_monitors!($node_b, 1);
3974 if $fail_backwards {
3975 assert!($node_a.node.get_and_clear_pending_events().is_empty());
3976 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3978 (extra_msg_option, bs_revoke_and_ack)
3981 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3983 check_added_monitors!($node_a, 0);
3984 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3985 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3986 check_added_monitors!($node_a, 1);
3987 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3988 assert!(extra_msg_option.is_none());
3992 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3994 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3995 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3997 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3998 if $fail_backwards {
3999 assert_eq!(added_monitors.len(), 2);
4000 assert!(added_monitors[0].0 != added_monitors[1].0);
4002 assert_eq!(added_monitors.len(), 1);
4004 added_monitors.clear();
4009 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4011 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4014 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4016 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4017 if $fail_backwards {
4018 let channel_state = $node_a.node.channel_state.lock().unwrap();
4019 assert_eq!(channel_state.pending_msg_events.len(), 1);
4020 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4021 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4022 } else { panic!("Unexpected event"); }
4024 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4030 macro_rules! get_payment_preimage_hash {
4033 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4034 *$node.network_payment_count.borrow_mut() += 1;
4035 let mut payment_hash = PaymentHash([0; 32]);
4036 let mut sha = Sha256::new();
4037 sha.input(&payment_preimage.0[..]);
4038 sha.result(&mut payment_hash.0[..]);
4039 (payment_preimage, payment_hash)
4044 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4045 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4047 let mut payment_event = {
4048 origin_node.node.send_payment(route, our_payment_hash).unwrap();
4049 check_added_monitors!(origin_node, 1);
4051 let mut events = origin_node.node.get_and_clear_pending_msg_events();
4052 assert_eq!(events.len(), 1);
4053 SendEvent::from_event(events.remove(0))
4055 let mut prev_node = origin_node;
4057 for (idx, &node) in expected_route.iter().enumerate() {
4058 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4060 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4061 check_added_monitors!(node, 0);
4062 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4064 let events_1 = node.node.get_and_clear_pending_events();
4065 assert_eq!(events_1.len(), 1);
4067 Event::PendingHTLCsForwardable { .. } => { },
4068 _ => panic!("Unexpected event"),
4071 node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4072 node.node.process_pending_htlc_forwards();
4074 if idx == expected_route.len() - 1 {
4075 let events_2 = node.node.get_and_clear_pending_events();
4076 assert_eq!(events_2.len(), 1);
4078 Event::PaymentReceived { ref payment_hash, amt } => {
4079 assert_eq!(our_payment_hash, *payment_hash);
4080 assert_eq!(amt, recv_value);
4082 _ => panic!("Unexpected event"),
4085 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4086 assert_eq!(events_2.len(), 1);
4087 check_added_monitors!(node, 1);
4088 payment_event = SendEvent::from_event(events_2.remove(0));
4089 assert_eq!(payment_event.msgs.len(), 1);
4095 (our_payment_preimage, our_payment_hash)
4098 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4099 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4100 check_added_monitors!(expected_route.last().unwrap(), 1);
4102 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4103 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4104 macro_rules! get_next_msgs {
4107 let events = $node.node.get_and_clear_pending_msg_events();
4108 assert_eq!(events.len(), 1);
4110 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 } } => {
4111 assert!(update_add_htlcs.is_empty());
4112 assert_eq!(update_fulfill_htlcs.len(), 1);
4113 assert!(update_fail_htlcs.is_empty());
4114 assert!(update_fail_malformed_htlcs.is_empty());
4115 assert!(update_fee.is_none());
4116 expected_next_node = node_id.clone();
4117 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4119 _ => panic!("Unexpected event"),
4125 macro_rules! last_update_fulfill_dance {
4126 ($node: expr, $prev_node: expr) => {
4128 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4129 check_added_monitors!($node, 0);
4130 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4131 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4135 macro_rules! mid_update_fulfill_dance {
4136 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4138 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4139 check_added_monitors!($node, 1);
4140 let new_next_msgs = if $new_msgs {
4141 get_next_msgs!($node)
4143 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4146 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4147 next_msgs = new_next_msgs;
4152 let mut prev_node = expected_route.last().unwrap();
4153 for (idx, node) in expected_route.iter().rev().enumerate() {
4154 assert_eq!(expected_next_node, node.node.get_our_node_id());
4155 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4156 if next_msgs.is_some() {
4157 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4158 } else if update_next_msgs {
4159 next_msgs = get_next_msgs!(node);
4161 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4163 if !skip_last && idx == expected_route.len() - 1 {
4164 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4171 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4172 let events = origin_node.node.get_and_clear_pending_events();
4173 assert_eq!(events.len(), 1);
4175 Event::PaymentSent { payment_preimage } => {
4176 assert_eq!(payment_preimage, our_payment_preimage);
4178 _ => panic!("Unexpected event"),
4183 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4184 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4187 const TEST_FINAL_CLTV: u32 = 32;
4189 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4190 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();
4191 assert_eq!(route.hops.len(), expected_route.len());
4192 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4193 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4196 send_along_route(origin_node, route, expected_route, recv_value)
4199 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4200 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();
4201 assert_eq!(route.hops.len(), expected_route.len());
4202 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4203 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4206 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4208 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4210 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4211 _ => panic!("Unknown error variants"),
4215 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4216 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4217 claim_payment(&origin, expected_route, our_payment_preimage);
4220 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4221 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4222 check_added_monitors!(expected_route.last().unwrap(), 1);
4224 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4225 macro_rules! update_fail_dance {
4226 ($node: expr, $prev_node: expr, $last_node: expr) => {
4228 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4229 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4234 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4235 let mut prev_node = expected_route.last().unwrap();
4236 for (idx, node) in expected_route.iter().rev().enumerate() {
4237 assert_eq!(expected_next_node, node.node.get_our_node_id());
4238 if next_msgs.is_some() {
4239 // We may be the "last node" for the purpose of the commitment dance if we're
4240 // skipping the last node (implying it is disconnected) and we're the
4241 // second-to-last node!
4242 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4245 let events = node.node.get_and_clear_pending_msg_events();
4246 if !skip_last || idx != expected_route.len() - 1 {
4247 assert_eq!(events.len(), 1);
4249 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 } } => {
4250 assert!(update_add_htlcs.is_empty());
4251 assert!(update_fulfill_htlcs.is_empty());
4252 assert_eq!(update_fail_htlcs.len(), 1);
4253 assert!(update_fail_malformed_htlcs.is_empty());
4254 assert!(update_fee.is_none());
4255 expected_next_node = node_id.clone();
4256 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4258 _ => panic!("Unexpected event"),
4261 assert!(events.is_empty());
4263 if !skip_last && idx == expected_route.len() - 1 {
4264 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4271 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4273 let events = origin_node.node.get_and_clear_pending_events();
4274 assert_eq!(events.len(), 1);
4276 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4277 assert_eq!(payment_hash, our_payment_hash);
4278 assert!(rejected_by_dest);
4280 _ => panic!("Unexpected event"),
4285 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4286 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4289 fn create_network(node_count: usize) -> Vec<Node> {
4290 let mut nodes = Vec::new();
4291 let mut rng = thread_rng();
4292 let secp_ctx = Secp256k1::new();
4294 let chan_count = Rc::new(RefCell::new(0));
4295 let payment_count = Rc::new(RefCell::new(0));
4297 for i in 0..node_count {
4298 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4299 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4300 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4301 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4302 let mut seed = [0; 32];
4303 rng.fill_bytes(&mut seed);
4304 let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4305 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4306 let mut config = UserConfig::new();
4307 config.channel_options.announced_channel = true;
4308 config.channel_limits.force_announced_channel_preference = false;
4309 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();
4310 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4311 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4312 network_payment_count: payment_count.clone(),
4313 network_chan_count: chan_count.clone(),
4321 fn test_async_inbound_update_fee() {
4322 let mut nodes = create_network(2);
4323 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4324 let channel_id = chan.2;
4327 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4331 // send (1) commitment_signed -.
4332 // <- update_add_htlc/commitment_signed
4333 // send (2) RAA (awaiting remote revoke) -.
4334 // (1) commitment_signed is delivered ->
4335 // .- send (3) RAA (awaiting remote revoke)
4336 // (2) RAA is delivered ->
4337 // .- send (4) commitment_signed
4338 // <- (3) RAA is delivered
4339 // send (5) commitment_signed -.
4340 // <- (4) commitment_signed is delivered
4342 // (5) commitment_signed is delivered ->
4344 // (6) RAA is delivered ->
4346 // First nodes[0] generates an update_fee
4347 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4348 check_added_monitors!(nodes[0], 1);
4350 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4351 assert_eq!(events_0.len(), 1);
4352 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4353 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4354 (update_fee.as_ref(), commitment_signed)
4356 _ => panic!("Unexpected event"),
4359 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4361 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4362 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4363 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();
4364 check_added_monitors!(nodes[1], 1);
4366 let payment_event = {
4367 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4368 assert_eq!(events_1.len(), 1);
4369 SendEvent::from_event(events_1.remove(0))
4371 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4372 assert_eq!(payment_event.msgs.len(), 1);
4374 // ...now when the messages get delivered everyone should be happy
4375 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4376 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4377 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4378 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4379 check_added_monitors!(nodes[0], 1);
4381 // deliver(1), generate (3):
4382 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4383 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4384 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4385 check_added_monitors!(nodes[1], 1);
4387 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4388 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4389 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4390 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4391 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4392 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4393 assert!(bs_update.update_fee.is_none()); // (4)
4394 check_added_monitors!(nodes[1], 1);
4396 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4397 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4398 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4399 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4400 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4401 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4402 assert!(as_update.update_fee.is_none()); // (5)
4403 check_added_monitors!(nodes[0], 1);
4405 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4406 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4407 // only (6) so get_event_msg's assert(len == 1) passes
4408 check_added_monitors!(nodes[0], 1);
4410 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4411 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4412 check_added_monitors!(nodes[1], 1);
4414 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4415 check_added_monitors!(nodes[0], 1);
4417 let events_2 = nodes[0].node.get_and_clear_pending_events();
4418 assert_eq!(events_2.len(), 1);
4420 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4421 _ => panic!("Unexpected event"),
4424 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4425 check_added_monitors!(nodes[1], 1);
4429 fn test_update_fee_unordered_raa() {
4430 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4431 // crash in an earlier version of the update_fee patch)
4432 let mut nodes = create_network(2);
4433 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4434 let channel_id = chan.2;
4437 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4439 // First nodes[0] generates an update_fee
4440 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4441 check_added_monitors!(nodes[0], 1);
4443 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4444 assert_eq!(events_0.len(), 1);
4445 let update_msg = match events_0[0] { // (1)
4446 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4449 _ => panic!("Unexpected event"),
4452 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4454 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4455 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4456 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();
4457 check_added_monitors!(nodes[1], 1);
4459 let payment_event = {
4460 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4461 assert_eq!(events_1.len(), 1);
4462 SendEvent::from_event(events_1.remove(0))
4464 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4465 assert_eq!(payment_event.msgs.len(), 1);
4467 // ...now when the messages get delivered everyone should be happy
4468 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4469 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4470 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4471 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4472 check_added_monitors!(nodes[0], 1);
4474 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4475 check_added_monitors!(nodes[1], 1);
4477 // We can't continue, sadly, because our (1) now has a bogus signature
4481 fn test_multi_flight_update_fee() {
4482 let nodes = create_network(2);
4483 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4484 let channel_id = chan.2;
4487 // update_fee/commitment_signed ->
4488 // .- send (1) RAA and (2) commitment_signed
4489 // update_fee (never committed) ->
4490 // (3) update_fee ->
4491 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4492 // don't track which updates correspond to which revoke_and_ack responses so we're in
4493 // AwaitingRAA mode and will not generate the update_fee yet.
4494 // <- (1) RAA delivered
4495 // (3) is generated and send (4) CS -.
4496 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4497 // know the per_commitment_point to use for it.
4498 // <- (2) commitment_signed delivered
4499 // revoke_and_ack ->
4500 // B should send no response here
4501 // (4) commitment_signed delivered ->
4502 // <- RAA/commitment_signed delivered
4503 // revoke_and_ack ->
4505 // First nodes[0] generates an update_fee
4506 let initial_feerate = get_feerate!(nodes[0], channel_id);
4507 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4508 check_added_monitors!(nodes[0], 1);
4510 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4511 assert_eq!(events_0.len(), 1);
4512 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4513 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4514 (update_fee.as_ref().unwrap(), commitment_signed)
4516 _ => panic!("Unexpected event"),
4519 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4520 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4521 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4522 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4523 check_added_monitors!(nodes[1], 1);
4525 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4527 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4528 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4529 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4531 // Create the (3) update_fee message that nodes[0] will generate before it does...
4532 let mut update_msg_2 = msgs::UpdateFee {
4533 channel_id: update_msg_1.channel_id.clone(),
4534 feerate_per_kw: (initial_feerate + 30) as u32,
4537 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4539 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4541 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4543 // Deliver (1), generating (3) and (4)
4544 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4545 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4546 check_added_monitors!(nodes[0], 1);
4547 assert!(as_second_update.update_add_htlcs.is_empty());
4548 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4549 assert!(as_second_update.update_fail_htlcs.is_empty());
4550 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4551 // Check that the update_fee newly generated matches what we delivered:
4552 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4553 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4555 // Deliver (2) commitment_signed
4556 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4557 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4558 check_added_monitors!(nodes[0], 1);
4559 // No commitment_signed so get_event_msg's assert(len == 1) passes
4561 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4562 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4563 check_added_monitors!(nodes[1], 1);
4566 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4567 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4568 check_added_monitors!(nodes[1], 1);
4570 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4571 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4572 check_added_monitors!(nodes[0], 1);
4574 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4575 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4576 // No commitment_signed so get_event_msg's assert(len == 1) passes
4577 check_added_monitors!(nodes[0], 1);
4579 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4580 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4581 check_added_monitors!(nodes[1], 1);
4585 fn test_update_fee_vanilla() {
4586 let nodes = create_network(2);
4587 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4588 let channel_id = chan.2;
4590 let feerate = get_feerate!(nodes[0], channel_id);
4591 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4592 check_added_monitors!(nodes[0], 1);
4594 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4595 assert_eq!(events_0.len(), 1);
4596 let (update_msg, commitment_signed) = match events_0[0] {
4597 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 } } => {
4598 (update_fee.as_ref(), commitment_signed)
4600 _ => panic!("Unexpected event"),
4602 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4604 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4605 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4606 check_added_monitors!(nodes[1], 1);
4608 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4609 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4610 check_added_monitors!(nodes[0], 1);
4612 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4613 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4614 // No commitment_signed so get_event_msg's assert(len == 1) passes
4615 check_added_monitors!(nodes[0], 1);
4617 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4618 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4619 check_added_monitors!(nodes[1], 1);
4623 fn test_update_fee_that_funder_cannot_afford() {
4624 let nodes = create_network(2);
4625 let channel_value = 1888;
4626 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4627 let channel_id = chan.2;
4630 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4631 check_added_monitors!(nodes[0], 1);
4632 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4634 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4636 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4638 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4639 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4641 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4642 let chan = chan_lock.by_id.get(&channel_id).unwrap();
4644 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4645 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4646 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4647 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4648 actual_fee = channel_value - actual_fee;
4649 assert_eq!(total_fee, actual_fee);
4652 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4653 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4654 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4655 check_added_monitors!(nodes[0], 1);
4657 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4659 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4661 //While producing the commitment_signed response after handling a received update_fee request the
4662 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4663 //Should produce and error.
4664 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4666 assert!(match err.err {
4667 "Funding remote cannot afford proposed new fee" => true,
4671 //clear the message we could not handle
4672 nodes[1].node.get_and_clear_pending_msg_events();
4676 fn test_update_fee_with_fundee_update_add_htlc() {
4677 let mut nodes = create_network(2);
4678 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4679 let channel_id = chan.2;
4682 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4684 let feerate = get_feerate!(nodes[0], channel_id);
4685 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4686 check_added_monitors!(nodes[0], 1);
4688 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4689 assert_eq!(events_0.len(), 1);
4690 let (update_msg, commitment_signed) = match events_0[0] {
4691 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 } } => {
4692 (update_fee.as_ref(), commitment_signed)
4694 _ => panic!("Unexpected event"),
4696 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4697 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4698 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4699 check_added_monitors!(nodes[1], 1);
4701 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4703 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4705 // nothing happens since node[1] is in AwaitingRemoteRevoke
4706 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4708 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4709 assert_eq!(added_monitors.len(), 0);
4710 added_monitors.clear();
4712 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4713 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4714 // node[1] has nothing to do
4716 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4717 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4718 check_added_monitors!(nodes[0], 1);
4720 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4721 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4722 // No commitment_signed so get_event_msg's assert(len == 1) passes
4723 check_added_monitors!(nodes[0], 1);
4724 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4725 check_added_monitors!(nodes[1], 1);
4726 // AwaitingRemoteRevoke ends here
4728 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4729 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4730 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4731 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4732 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4733 assert_eq!(commitment_update.update_fee.is_none(), true);
4735 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4736 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4737 check_added_monitors!(nodes[0], 1);
4738 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4740 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4741 check_added_monitors!(nodes[1], 1);
4742 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4744 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4745 check_added_monitors!(nodes[1], 1);
4746 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4747 // No commitment_signed so get_event_msg's assert(len == 1) passes
4749 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4750 check_added_monitors!(nodes[0], 1);
4751 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4753 let events = nodes[0].node.get_and_clear_pending_events();
4754 assert_eq!(events.len(), 1);
4756 Event::PendingHTLCsForwardable { .. } => { },
4757 _ => panic!("Unexpected event"),
4759 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4760 nodes[0].node.process_pending_htlc_forwards();
4762 let events = nodes[0].node.get_and_clear_pending_events();
4763 assert_eq!(events.len(), 1);
4765 Event::PaymentReceived { .. } => { },
4766 _ => panic!("Unexpected event"),
4769 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4771 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4772 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4773 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4777 fn test_update_fee() {
4778 let nodes = create_network(2);
4779 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4780 let channel_id = chan.2;
4783 // (1) update_fee/commitment_signed ->
4784 // <- (2) revoke_and_ack
4785 // .- send (3) commitment_signed
4786 // (4) update_fee/commitment_signed ->
4787 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4788 // <- (3) commitment_signed delivered
4789 // send (6) revoke_and_ack -.
4790 // <- (5) deliver revoke_and_ack
4791 // (6) deliver revoke_and_ack ->
4792 // .- send (7) commitment_signed in response to (4)
4793 // <- (7) deliver commitment_signed
4794 // revoke_and_ack ->
4796 // Create and deliver (1)...
4797 let feerate = get_feerate!(nodes[0], channel_id);
4798 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4799 check_added_monitors!(nodes[0], 1);
4801 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4802 assert_eq!(events_0.len(), 1);
4803 let (update_msg, commitment_signed) = match events_0[0] {
4804 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 } } => {
4805 (update_fee.as_ref(), commitment_signed)
4807 _ => panic!("Unexpected event"),
4809 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4811 // Generate (2) and (3):
4812 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4813 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4814 check_added_monitors!(nodes[1], 1);
4817 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4818 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4819 check_added_monitors!(nodes[0], 1);
4821 // Create and deliver (4)...
4822 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4823 check_added_monitors!(nodes[0], 1);
4824 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4825 assert_eq!(events_0.len(), 1);
4826 let (update_msg, commitment_signed) = match events_0[0] {
4827 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 } } => {
4828 (update_fee.as_ref(), commitment_signed)
4830 _ => panic!("Unexpected event"),
4833 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4834 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4835 check_added_monitors!(nodes[1], 1);
4837 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4838 // No commitment_signed so get_event_msg's assert(len == 1) passes
4840 // Handle (3), creating (6):
4841 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4842 check_added_monitors!(nodes[0], 1);
4843 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4844 // No commitment_signed so get_event_msg's assert(len == 1) passes
4847 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4848 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4849 check_added_monitors!(nodes[0], 1);
4851 // Deliver (6), creating (7):
4852 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4853 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4854 assert!(commitment_update.update_add_htlcs.is_empty());
4855 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4856 assert!(commitment_update.update_fail_htlcs.is_empty());
4857 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4858 assert!(commitment_update.update_fee.is_none());
4859 check_added_monitors!(nodes[1], 1);
4862 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4863 check_added_monitors!(nodes[0], 1);
4864 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4865 // No commitment_signed so get_event_msg's assert(len == 1) passes
4867 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4868 check_added_monitors!(nodes[1], 1);
4869 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4871 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4872 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4873 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4877 fn pre_funding_lock_shutdown_test() {
4878 // Test sending a shutdown prior to funding_locked after funding generation
4879 let nodes = create_network(2);
4880 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4881 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4882 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4883 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4885 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4886 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4887 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4888 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4889 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4891 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4892 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4893 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4894 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4895 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4896 assert!(node_0_none.is_none());
4898 assert!(nodes[0].node.list_channels().is_empty());
4899 assert!(nodes[1].node.list_channels().is_empty());
4903 fn updates_shutdown_wait() {
4904 // Test sending a shutdown with outstanding updates pending
4905 let mut nodes = create_network(3);
4906 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4907 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4908 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4909 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4911 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4913 nodes[0].node.close_channel(&chan_1.2).unwrap();
4914 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4915 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4916 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4917 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4919 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4920 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4922 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4923 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4924 else { panic!("New sends should fail!") };
4925 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4926 else { panic!("New sends should fail!") };
4928 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4929 check_added_monitors!(nodes[2], 1);
4930 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4931 assert!(updates.update_add_htlcs.is_empty());
4932 assert!(updates.update_fail_htlcs.is_empty());
4933 assert!(updates.update_fail_malformed_htlcs.is_empty());
4934 assert!(updates.update_fee.is_none());
4935 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4936 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4937 check_added_monitors!(nodes[1], 1);
4938 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4939 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4941 assert!(updates_2.update_add_htlcs.is_empty());
4942 assert!(updates_2.update_fail_htlcs.is_empty());
4943 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4944 assert!(updates_2.update_fee.is_none());
4945 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4946 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4947 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4949 let events = nodes[0].node.get_and_clear_pending_events();
4950 assert_eq!(events.len(), 1);
4952 Event::PaymentSent { ref payment_preimage } => {
4953 assert_eq!(our_payment_preimage, *payment_preimage);
4955 _ => panic!("Unexpected event"),
4958 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4959 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4960 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4961 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4962 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4963 assert!(node_0_none.is_none());
4965 assert!(nodes[0].node.list_channels().is_empty());
4967 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4968 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4969 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4970 assert!(nodes[1].node.list_channels().is_empty());
4971 assert!(nodes[2].node.list_channels().is_empty());
4975 fn htlc_fail_async_shutdown() {
4976 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4977 let mut nodes = create_network(3);
4978 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4979 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4981 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4982 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4983 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4984 check_added_monitors!(nodes[0], 1);
4985 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4986 assert_eq!(updates.update_add_htlcs.len(), 1);
4987 assert!(updates.update_fulfill_htlcs.is_empty());
4988 assert!(updates.update_fail_htlcs.is_empty());
4989 assert!(updates.update_fail_malformed_htlcs.is_empty());
4990 assert!(updates.update_fee.is_none());
4992 nodes[1].node.close_channel(&chan_1.2).unwrap();
4993 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4994 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4995 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4997 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4998 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4999 check_added_monitors!(nodes[1], 1);
5000 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5001 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5003 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5004 assert!(updates_2.update_add_htlcs.is_empty());
5005 assert!(updates_2.update_fulfill_htlcs.is_empty());
5006 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5007 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5008 assert!(updates_2.update_fee.is_none());
5010 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5011 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5013 let events = nodes[0].node.get_and_clear_pending_events();
5014 assert_eq!(events.len(), 1);
5016 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
5017 assert_eq!(our_payment_hash, *payment_hash);
5018 assert!(!rejected_by_dest);
5020 _ => panic!("Unexpected event"),
5023 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5024 assert_eq!(msg_events.len(), 2);
5025 let node_0_closing_signed = match msg_events[0] {
5026 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5027 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5030 _ => panic!("Unexpected event"),
5032 match msg_events[1] {
5033 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5034 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5036 _ => panic!("Unexpected event"),
5039 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5040 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5041 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5042 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5043 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5044 assert!(node_0_none.is_none());
5046 assert!(nodes[0].node.list_channels().is_empty());
5048 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5049 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5050 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5051 assert!(nodes[1].node.list_channels().is_empty());
5052 assert!(nodes[2].node.list_channels().is_empty());
5055 fn do_test_shutdown_rebroadcast(recv_count: u8) {
5056 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5057 // messages delivered prior to disconnect
5058 let nodes = create_network(3);
5059 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5060 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5062 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5064 nodes[1].node.close_channel(&chan_1.2).unwrap();
5065 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5067 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5068 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5070 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5074 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5075 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5077 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5078 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5079 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5080 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5082 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5083 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5084 assert!(node_1_shutdown == node_1_2nd_shutdown);
5086 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5087 let node_0_2nd_shutdown = if recv_count > 0 {
5088 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5089 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5092 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5093 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5094 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5096 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5098 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5099 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5101 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5102 check_added_monitors!(nodes[2], 1);
5103 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5104 assert!(updates.update_add_htlcs.is_empty());
5105 assert!(updates.update_fail_htlcs.is_empty());
5106 assert!(updates.update_fail_malformed_htlcs.is_empty());
5107 assert!(updates.update_fee.is_none());
5108 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5109 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5110 check_added_monitors!(nodes[1], 1);
5111 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5112 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5114 assert!(updates_2.update_add_htlcs.is_empty());
5115 assert!(updates_2.update_fail_htlcs.is_empty());
5116 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5117 assert!(updates_2.update_fee.is_none());
5118 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5119 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5120 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5122 let events = nodes[0].node.get_and_clear_pending_events();
5123 assert_eq!(events.len(), 1);
5125 Event::PaymentSent { ref payment_preimage } => {
5126 assert_eq!(our_payment_preimage, *payment_preimage);
5128 _ => panic!("Unexpected event"),
5131 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5133 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5134 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5135 assert!(node_1_closing_signed.is_some());
5138 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5139 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5141 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5142 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5143 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5144 if recv_count == 0 {
5145 // If all closing_signeds weren't delivered we can just resume where we left off...
5146 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5148 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5149 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5150 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5152 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5153 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5154 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5156 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5157 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5159 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5160 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5161 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5163 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5164 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5165 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5166 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5167 assert!(node_0_none.is_none());
5169 // If one node, however, received + responded with an identical closing_signed we end
5170 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5171 // There isn't really anything better we can do simply, but in the future we might
5172 // explore storing a set of recently-closed channels that got disconnected during
5173 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5174 // give our counterparty enough time to (potentially) broadcast a cooperative closing
5176 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5178 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5179 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5180 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5181 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5182 assert_eq!(*channel_id, chan_1.2);
5183 } else { panic!("Needed SendErrorMessage close"); }
5185 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5186 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5187 // closing_signed so we do it ourselves
5188 let events = nodes[0].node.get_and_clear_pending_msg_events();
5189 assert_eq!(events.len(), 1);
5191 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5192 assert_eq!(msg.contents.flags & 2, 2);
5194 _ => panic!("Unexpected event"),
5198 assert!(nodes[0].node.list_channels().is_empty());
5200 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5201 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5202 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5203 assert!(nodes[1].node.list_channels().is_empty());
5204 assert!(nodes[2].node.list_channels().is_empty());
5208 fn test_shutdown_rebroadcast() {
5209 do_test_shutdown_rebroadcast(0);
5210 do_test_shutdown_rebroadcast(1);
5211 do_test_shutdown_rebroadcast(2);
5215 fn fake_network_test() {
5216 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5217 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5218 let nodes = create_network(4);
5220 // Create some initial channels
5221 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5222 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5223 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5225 // Rebalance the network a bit by relaying one payment through all the channels...
5226 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5227 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5228 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5229 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5231 // Send some more payments
5232 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5233 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5234 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5236 // Test failure packets
5237 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5238 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5240 // Add a new channel that skips 3
5241 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5243 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5244 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5245 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5246 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5247 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5248 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5249 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5251 // Do some rebalance loop payments, simultaneously
5252 let mut hops = Vec::with_capacity(3);
5253 hops.push(RouteHop {
5254 pubkey: nodes[2].node.get_our_node_id(),
5255 short_channel_id: chan_2.0.contents.short_channel_id,
5257 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5259 hops.push(RouteHop {
5260 pubkey: nodes[3].node.get_our_node_id(),
5261 short_channel_id: chan_3.0.contents.short_channel_id,
5263 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5265 hops.push(RouteHop {
5266 pubkey: nodes[1].node.get_our_node_id(),
5267 short_channel_id: chan_4.0.contents.short_channel_id,
5269 cltv_expiry_delta: TEST_FINAL_CLTV,
5271 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;
5272 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;
5273 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5275 let mut hops = Vec::with_capacity(3);
5276 hops.push(RouteHop {
5277 pubkey: nodes[3].node.get_our_node_id(),
5278 short_channel_id: chan_4.0.contents.short_channel_id,
5280 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5282 hops.push(RouteHop {
5283 pubkey: nodes[2].node.get_our_node_id(),
5284 short_channel_id: chan_3.0.contents.short_channel_id,
5286 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5288 hops.push(RouteHop {
5289 pubkey: nodes[1].node.get_our_node_id(),
5290 short_channel_id: chan_2.0.contents.short_channel_id,
5292 cltv_expiry_delta: TEST_FINAL_CLTV,
5294 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;
5295 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;
5296 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5298 // Claim the rebalances...
5299 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5300 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5302 // Add a duplicate new channel from 2 to 4
5303 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5305 // Send some payments across both channels
5306 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5307 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5308 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5310 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5312 //TODO: Test that routes work again here as we've been notified that the channel is full
5314 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5315 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5316 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5318 // Close down the channels...
5319 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5320 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5321 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5322 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5323 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5327 fn duplicate_htlc_test() {
5328 // Test that we accept duplicate payment_hash HTLCs across the network and that
5329 // claiming/failing them are all separate and don't effect each other
5330 let mut nodes = create_network(6);
5332 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5333 create_announced_chan_between_nodes(&nodes, 0, 3);
5334 create_announced_chan_between_nodes(&nodes, 1, 3);
5335 create_announced_chan_between_nodes(&nodes, 2, 3);
5336 create_announced_chan_between_nodes(&nodes, 3, 4);
5337 create_announced_chan_between_nodes(&nodes, 3, 5);
5339 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5341 *nodes[0].network_payment_count.borrow_mut() -= 1;
5342 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5344 *nodes[0].network_payment_count.borrow_mut() -= 1;
5345 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5347 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5348 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5349 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5352 #[derive(PartialEq)]
5353 enum HTLCType { NONE, TIMEOUT, SUCCESS }
5354 /// Tests that the given node has broadcast transactions for the given Channel
5356 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5357 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5358 /// broadcast and the revoked outputs were claimed.
5360 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5361 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5363 /// All broadcast transactions must be accounted for in one of the above three types of we'll
5365 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5366 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5367 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5369 let mut res = Vec::with_capacity(2);
5370 node_txn.retain(|tx| {
5371 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5372 check_spends!(tx, chan.3.clone());
5373 if commitment_tx.is_none() {
5374 res.push(tx.clone());
5379 if let Some(explicit_tx) = commitment_tx {
5380 res.push(explicit_tx.clone());
5383 assert_eq!(res.len(), 1);
5385 if has_htlc_tx != HTLCType::NONE {
5386 node_txn.retain(|tx| {
5387 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5388 check_spends!(tx, res[0].clone());
5389 if has_htlc_tx == HTLCType::TIMEOUT {
5390 assert!(tx.lock_time != 0);
5392 assert!(tx.lock_time == 0);
5394 res.push(tx.clone());
5398 assert!(res.len() == 2 || res.len() == 3);
5400 assert_eq!(res[1], res[2]);
5404 assert!(node_txn.is_empty());
5408 /// Tests that the given node has broadcast a claim transaction against the provided revoked
5409 /// HTLC transaction.
5410 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5411 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5412 assert_eq!(node_txn.len(), 1);
5413 node_txn.retain(|tx| {
5414 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5415 check_spends!(tx, revoked_tx.clone());
5419 assert!(node_txn.is_empty());
5422 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5423 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5425 assert!(node_txn.len() >= 1);
5426 assert_eq!(node_txn[0].input.len(), 1);
5427 let mut found_prev = false;
5429 for tx in prev_txn {
5430 if node_txn[0].input[0].previous_output.txid == tx.txid() {
5431 check_spends!(node_txn[0], tx.clone());
5432 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5433 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5439 assert!(found_prev);
5441 let mut res = Vec::new();
5442 mem::swap(&mut *node_txn, &mut res);
5446 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5447 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5448 assert_eq!(events_1.len(), 1);
5449 let as_update = match events_1[0] {
5450 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5453 _ => panic!("Unexpected event"),
5456 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5457 assert_eq!(events_2.len(), 1);
5458 let bs_update = match events_2[0] {
5459 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5462 _ => panic!("Unexpected event"),
5466 node.router.handle_channel_update(&as_update).unwrap();
5467 node.router.handle_channel_update(&bs_update).unwrap();
5471 macro_rules! expect_pending_htlcs_forwardable {
5473 let events = $node.node.get_and_clear_pending_events();
5474 assert_eq!(events.len(), 1);
5476 Event::PendingHTLCsForwardable { .. } => { },
5477 _ => panic!("Unexpected event"),
5479 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5480 $node.node.process_pending_htlc_forwards();
5484 fn do_channel_reserve_test(test_recv: bool) {
5486 use std::sync::atomic::Ordering;
5487 use ln::msgs::HandleError;
5489 macro_rules! get_channel_value_stat {
5490 ($node: expr, $channel_id: expr) => {{
5491 let chan_lock = $node.node.channel_state.lock().unwrap();
5492 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5493 chan.get_value_stat()
5497 let mut nodes = create_network(3);
5498 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5499 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5501 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5502 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5504 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5505 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5507 macro_rules! get_route_and_payment_hash {
5508 ($recv_value: expr) => {{
5509 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5510 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5511 (route, payment_hash, payment_preimage)
5515 macro_rules! expect_forward {
5517 let mut events = $node.node.get_and_clear_pending_msg_events();
5518 assert_eq!(events.len(), 1);
5519 check_added_monitors!($node, 1);
5520 let payment_event = SendEvent::from_event(events.remove(0));
5525 macro_rules! expect_payment_received {
5526 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5527 let events = $node.node.get_and_clear_pending_events();
5528 assert_eq!(events.len(), 1);
5530 Event::PaymentReceived { ref payment_hash, amt } => {
5531 assert_eq!($expected_payment_hash, *payment_hash);
5532 assert_eq!($expected_recv_value, amt);
5534 _ => panic!("Unexpected event"),
5539 let feemsat = 239; // somehow we know?
5540 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5542 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5544 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5546 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5547 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5548 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5550 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5551 _ => panic!("Unknown error variants"),
5555 let mut htlc_id = 0;
5556 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5557 // nodes[0]'s wealth
5559 let amt_msat = recv_value_0 + total_fee_msat;
5560 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5563 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5566 let (stat01_, stat11_, stat12_, stat22_) = (
5567 get_channel_value_stat!(nodes[0], chan_1.2),
5568 get_channel_value_stat!(nodes[1], chan_1.2),
5569 get_channel_value_stat!(nodes[1], chan_2.2),
5570 get_channel_value_stat!(nodes[2], chan_2.2),
5573 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5574 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5575 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5576 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5577 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5581 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5582 // attempt to get channel_reserve violation
5583 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5584 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5586 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5587 _ => panic!("Unknown error variants"),
5591 // adding pending output
5592 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5593 let amt_msat_1 = recv_value_1 + total_fee_msat;
5595 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5596 let payment_event_1 = {
5597 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5598 check_added_monitors!(nodes[0], 1);
5600 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5601 assert_eq!(events.len(), 1);
5602 SendEvent::from_event(events.remove(0))
5604 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5606 // channel reserve test with htlc pending output > 0
5607 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5609 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5610 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5611 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5612 _ => panic!("Unknown error variants"),
5617 // test channel_reserve test on nodes[1] side
5618 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5620 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5621 let secp_ctx = Secp256k1::new();
5622 let session_priv = SecretKey::from_slice(&secp_ctx, &{
5623 let mut session_key = [0; 32];
5624 rng::fill_bytes(&mut session_key);
5626 }).expect("RNG is bad!");
5628 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5629 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5630 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5631 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5632 let msg = msgs::UpdateAddHTLC {
5633 channel_id: chan_1.2,
5635 amount_msat: htlc_msat,
5636 payment_hash: our_payment_hash,
5637 cltv_expiry: htlc_cltv,
5638 onion_routing_packet: onion_packet,
5642 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5644 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5646 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5647 assert_eq!(nodes[1].node.list_channels().len(), 1);
5648 assert_eq!(nodes[1].node.list_channels().len(), 1);
5649 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5650 assert_eq!(channel_close_broadcast.len(), 1);
5651 match channel_close_broadcast[0] {
5652 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5653 assert_eq!(msg.contents.flags & 2, 2);
5655 _ => panic!("Unexpected event"),
5661 // split the rest to test holding cell
5662 let recv_value_21 = recv_value_2/2;
5663 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5665 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5666 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);
5669 // now see if they go through on both sides
5670 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5671 // but this will stuck in the holding cell
5672 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5673 check_added_monitors!(nodes[0], 0);
5674 let events = nodes[0].node.get_and_clear_pending_events();
5675 assert_eq!(events.len(), 0);
5677 // test with outbound holding cell amount > 0
5679 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5680 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5681 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5682 _ => panic!("Unknown error variants"),
5686 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5687 // this will also stuck in the holding cell
5688 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5689 check_added_monitors!(nodes[0], 0);
5690 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5691 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5693 // flush the pending htlc
5694 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5695 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5696 check_added_monitors!(nodes[1], 1);
5698 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5699 check_added_monitors!(nodes[0], 1);
5700 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5702 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5703 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5704 // No commitment_signed so get_event_msg's assert(len == 1) passes
5705 check_added_monitors!(nodes[0], 1);
5707 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5708 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5709 check_added_monitors!(nodes[1], 1);
5711 expect_pending_htlcs_forwardable!(nodes[1]);
5713 let ref payment_event_11 = expect_forward!(nodes[1]);
5714 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5715 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5717 expect_pending_htlcs_forwardable!(nodes[2]);
5718 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5720 // flush the htlcs in the holding cell
5721 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5722 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5723 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5724 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5725 expect_pending_htlcs_forwardable!(nodes[1]);
5727 let ref payment_event_3 = expect_forward!(nodes[1]);
5728 assert_eq!(payment_event_3.msgs.len(), 2);
5729 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5730 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5732 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5733 expect_pending_htlcs_forwardable!(nodes[2]);
5735 let events = nodes[2].node.get_and_clear_pending_events();
5736 assert_eq!(events.len(), 2);
5738 Event::PaymentReceived { ref payment_hash, amt } => {
5739 assert_eq!(our_payment_hash_21, *payment_hash);
5740 assert_eq!(recv_value_21, amt);
5742 _ => panic!("Unexpected event"),
5745 Event::PaymentReceived { ref payment_hash, amt } => {
5746 assert_eq!(our_payment_hash_22, *payment_hash);
5747 assert_eq!(recv_value_22, amt);
5749 _ => panic!("Unexpected event"),
5752 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5753 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5754 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5756 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);
5757 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5758 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5759 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5761 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5762 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5766 fn channel_reserve_test() {
5767 do_channel_reserve_test(false);
5768 do_channel_reserve_test(true);
5772 fn channel_monitor_network_test() {
5773 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5774 // tests that ChannelMonitor is able to recover from various states.
5775 let nodes = create_network(5);
5777 // Create some initial channels
5778 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5779 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5780 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5781 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5783 // Rebalance the network a bit by relaying one payment through all the channels...
5784 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5785 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5786 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5787 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5789 // Simple case with no pending HTLCs:
5790 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5792 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5793 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5794 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5795 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5797 get_announce_close_broadcast_events(&nodes, 0, 1);
5798 assert_eq!(nodes[0].node.list_channels().len(), 0);
5799 assert_eq!(nodes[1].node.list_channels().len(), 1);
5801 // One pending HTLC is discarded by the force-close:
5802 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5804 // Simple case of one pending HTLC to HTLC-Timeout
5805 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5807 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5808 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5809 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5810 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5812 get_announce_close_broadcast_events(&nodes, 1, 2);
5813 assert_eq!(nodes[1].node.list_channels().len(), 0);
5814 assert_eq!(nodes[2].node.list_channels().len(), 1);
5816 macro_rules! claim_funds {
5817 ($node: expr, $prev_node: expr, $preimage: expr) => {
5819 assert!($node.node.claim_funds($preimage));
5820 check_added_monitors!($node, 1);
5822 let events = $node.node.get_and_clear_pending_msg_events();
5823 assert_eq!(events.len(), 1);
5825 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5826 assert!(update_add_htlcs.is_empty());
5827 assert!(update_fail_htlcs.is_empty());
5828 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5830 _ => panic!("Unexpected event"),
5836 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5837 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5838 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5840 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5842 // Claim the payment on nodes[3], giving it knowledge of the preimage
5843 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5845 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5846 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5848 check_preimage_claim(&nodes[3], &node_txn);
5850 get_announce_close_broadcast_events(&nodes, 2, 3);
5851 assert_eq!(nodes[2].node.list_channels().len(), 0);
5852 assert_eq!(nodes[3].node.list_channels().len(), 1);
5854 { // Cheat and reset nodes[4]'s height to 1
5855 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5856 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5859 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5860 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5861 // One pending HTLC to time out:
5862 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5863 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5867 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5868 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5869 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5870 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5871 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5874 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5876 // Claim the payment on nodes[4], giving it knowledge of the preimage
5877 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5879 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5880 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5881 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5882 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5883 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5886 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5888 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5889 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5891 check_preimage_claim(&nodes[4], &node_txn);
5893 get_announce_close_broadcast_events(&nodes, 3, 4);
5894 assert_eq!(nodes[3].node.list_channels().len(), 0);
5895 assert_eq!(nodes[4].node.list_channels().len(), 0);
5899 fn test_justice_tx() {
5900 // Test justice txn built on revoked HTLC-Success tx, against both sides
5902 let nodes = create_network(2);
5903 // Create some new channels:
5904 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5906 // A pending HTLC which will be revoked:
5907 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5908 // Get the will-be-revoked local txn from nodes[0]
5909 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5910 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5911 assert_eq!(revoked_local_txn[0].input.len(), 1);
5912 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5913 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5914 assert_eq!(revoked_local_txn[1].input.len(), 1);
5915 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5916 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5917 // Revoke the old state
5918 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5921 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5922 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5924 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5925 assert_eq!(node_txn.len(), 3);
5926 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5927 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5929 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5930 node_txn.swap_remove(0);
5932 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5934 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5935 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5936 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5937 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5938 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5940 get_announce_close_broadcast_events(&nodes, 0, 1);
5942 assert_eq!(nodes[0].node.list_channels().len(), 0);
5943 assert_eq!(nodes[1].node.list_channels().len(), 0);
5945 // We test justice_tx build by A on B's revoked HTLC-Success tx
5946 // Create some new channels:
5947 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5949 // A pending HTLC which will be revoked:
5950 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5951 // Get the will-be-revoked local txn from B
5952 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5953 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5954 assert_eq!(revoked_local_txn[0].input.len(), 1);
5955 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5956 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5957 // Revoke the old state
5958 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5960 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5961 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5963 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5964 assert_eq!(node_txn.len(), 3);
5965 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5966 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5968 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5969 node_txn.swap_remove(0);
5971 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5973 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5974 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5975 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5976 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5977 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5979 get_announce_close_broadcast_events(&nodes, 0, 1);
5980 assert_eq!(nodes[0].node.list_channels().len(), 0);
5981 assert_eq!(nodes[1].node.list_channels().len(), 0);
5985 fn revoked_output_claim() {
5986 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5987 // transaction is broadcast by its counterparty
5988 let nodes = create_network(2);
5989 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5990 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5991 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5992 assert_eq!(revoked_local_txn.len(), 1);
5993 // Only output is the full channel value back to nodes[0]:
5994 assert_eq!(revoked_local_txn[0].output.len(), 1);
5995 // Send a payment through, updating everyone's latest commitment txn
5996 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5998 // Inform nodes[1] that nodes[0] broadcast a stale tx
5999 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6000 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6001 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6002 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
6004 assert_eq!(node_txn[0], node_txn[2]);
6006 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6007 check_spends!(node_txn[1], chan_1.3.clone());
6009 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6010 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6011 get_announce_close_broadcast_events(&nodes, 0, 1);
6015 fn claim_htlc_outputs_shared_tx() {
6016 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6017 let nodes = create_network(2);
6019 // Create some new channel:
6020 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6022 // Rebalance the network to generate htlc in the two directions
6023 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6024 // 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
6025 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6026 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6028 // Get the will-be-revoked local txn from node[0]
6029 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6030 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6031 assert_eq!(revoked_local_txn[0].input.len(), 1);
6032 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6033 assert_eq!(revoked_local_txn[1].input.len(), 1);
6034 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6035 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6036 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6038 //Revoke the old state
6039 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6042 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6043 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6044 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6046 let events = nodes[1].node.get_and_clear_pending_events();
6047 assert_eq!(events.len(), 1);
6049 Event::PaymentFailed { payment_hash, .. } => {
6050 assert_eq!(payment_hash, payment_hash_2);
6052 _ => panic!("Unexpected event"),
6055 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6056 assert_eq!(node_txn.len(), 4);
6058 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6059 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6061 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6063 let mut witness_lens = BTreeSet::new();
6064 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6065 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6066 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6067 assert_eq!(witness_lens.len(), 3);
6068 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6069 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6070 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6072 // Next nodes[1] broadcasts its current local tx state:
6073 assert_eq!(node_txn[1].input.len(), 1);
6074 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6076 assert_eq!(node_txn[2].input.len(), 1);
6077 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6078 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6079 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6080 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6081 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6083 get_announce_close_broadcast_events(&nodes, 0, 1);
6084 assert_eq!(nodes[0].node.list_channels().len(), 0);
6085 assert_eq!(nodes[1].node.list_channels().len(), 0);
6089 fn claim_htlc_outputs_single_tx() {
6090 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6091 let nodes = create_network(2);
6093 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6095 // Rebalance the network to generate htlc in the two directions
6096 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6097 // 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
6098 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6099 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6100 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6102 // Get the will-be-revoked local txn from node[0]
6103 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6105 //Revoke the old state
6106 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6109 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6110 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6111 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6113 let events = nodes[1].node.get_and_clear_pending_events();
6114 assert_eq!(events.len(), 1);
6116 Event::PaymentFailed { payment_hash, .. } => {
6117 assert_eq!(payment_hash, payment_hash_2);
6119 _ => panic!("Unexpected event"),
6122 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6123 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)
6125 assert_eq!(node_txn[0], node_txn[7]);
6126 assert_eq!(node_txn[1], node_txn[8]);
6127 assert_eq!(node_txn[2], node_txn[9]);
6128 assert_eq!(node_txn[3], node_txn[10]);
6129 assert_eq!(node_txn[4], node_txn[11]);
6130 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6131 assert_eq!(node_txn[4], node_txn[6]);
6133 assert_eq!(node_txn[0].input.len(), 1);
6134 assert_eq!(node_txn[1].input.len(), 1);
6135 assert_eq!(node_txn[2].input.len(), 1);
6137 let mut revoked_tx_map = HashMap::new();
6138 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6139 node_txn[0].verify(&revoked_tx_map).unwrap();
6140 node_txn[1].verify(&revoked_tx_map).unwrap();
6141 node_txn[2].verify(&revoked_tx_map).unwrap();
6143 let mut witness_lens = BTreeSet::new();
6144 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6145 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6146 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6147 assert_eq!(witness_lens.len(), 3);
6148 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6149 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6150 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6152 assert_eq!(node_txn[3].input.len(), 1);
6153 check_spends!(node_txn[3], chan_1.3.clone());
6155 assert_eq!(node_txn[4].input.len(), 1);
6156 let witness_script = node_txn[4].input[0].witness.last().unwrap();
6157 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6158 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6159 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6160 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6162 get_announce_close_broadcast_events(&nodes, 0, 1);
6163 assert_eq!(nodes[0].node.list_channels().len(), 0);
6164 assert_eq!(nodes[1].node.list_channels().len(), 0);
6168 fn test_htlc_on_chain_success() {
6169 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6170 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6171 // broadcasting the right event to other nodes in payment path.
6172 // A --------------------> B ----------------------> C (preimage)
6173 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6174 // commitment transaction was broadcast.
6175 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6177 // B should be able to claim via preimage if A then broadcasts its local tx.
6178 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6179 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6180 // PaymentSent event).
6182 let nodes = create_network(3);
6184 // Create some initial channels
6185 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6186 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6188 // Rebalance the network a bit by relaying one payment through all the channels...
6189 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6190 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6192 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6193 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6195 // Broadcast legit commitment tx from C on B's chain
6196 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6197 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6198 assert_eq!(commitment_tx.len(), 1);
6199 check_spends!(commitment_tx[0], chan_2.3.clone());
6200 nodes[2].node.claim_funds(our_payment_preimage);
6201 check_added_monitors!(nodes[2], 1);
6202 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6203 assert!(updates.update_add_htlcs.is_empty());
6204 assert!(updates.update_fail_htlcs.is_empty());
6205 assert!(updates.update_fail_malformed_htlcs.is_empty());
6206 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6208 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6209 let events = nodes[2].node.get_and_clear_pending_msg_events();
6210 assert_eq!(events.len(), 1);
6212 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6213 _ => panic!("Unexpected event"),
6215 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6216 assert_eq!(node_txn.len(), 3);
6217 assert_eq!(node_txn[1], commitment_tx[0]);
6218 assert_eq!(node_txn[0], node_txn[2]);
6219 check_spends!(node_txn[0], commitment_tx[0].clone());
6220 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6221 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6222 assert_eq!(node_txn[0].lock_time, 0);
6224 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6225 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6226 let events = nodes[1].node.get_and_clear_pending_msg_events();
6228 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6229 assert_eq!(added_monitors.len(), 1);
6230 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6231 added_monitors.clear();
6233 assert_eq!(events.len(), 2);
6235 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6236 _ => panic!("Unexpected event"),
6239 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, .. } } => {
6240 assert!(update_add_htlcs.is_empty());
6241 assert!(update_fail_htlcs.is_empty());
6242 assert_eq!(update_fulfill_htlcs.len(), 1);
6243 assert!(update_fail_malformed_htlcs.is_empty());
6244 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6246 _ => panic!("Unexpected event"),
6249 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6250 // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6251 // timeout-claim of the output that nodes[2] just claimed via success.
6252 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)
6253 assert_eq!(node_txn.len(), 4);
6254 assert_eq!(node_txn[0], node_txn[3]);
6255 check_spends!(node_txn[0], commitment_tx[0].clone());
6256 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6257 assert_ne!(node_txn[0].lock_time, 0);
6258 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6259 check_spends!(node_txn[1], chan_2.3.clone());
6260 check_spends!(node_txn[2], node_txn[1].clone());
6261 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6262 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6263 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6264 assert_ne!(node_txn[2].lock_time, 0);
6268 // Broadcast legit commitment tx from A on B's chain
6269 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
6270 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6271 check_spends!(commitment_tx[0], chan_1.3.clone());
6272 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6273 let events = nodes[1].node.get_and_clear_pending_msg_events();
6274 assert_eq!(events.len(), 1);
6276 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6277 _ => panic!("Unexpected event"),
6279 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6280 assert_eq!(node_txn.len(), 3);
6281 assert_eq!(node_txn[0], node_txn[2]);
6282 check_spends!(node_txn[0], commitment_tx[0].clone());
6283 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6284 assert_eq!(node_txn[0].lock_time, 0);
6285 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6286 check_spends!(node_txn[1], chan_1.3.clone());
6287 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6288 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6289 // we already checked the same situation with A.
6291 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6292 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6293 let events = nodes[0].node.get_and_clear_pending_msg_events();
6294 assert_eq!(events.len(), 1);
6296 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6297 _ => panic!("Unexpected event"),
6299 let events = nodes[0].node.get_and_clear_pending_events();
6300 assert_eq!(events.len(), 1);
6302 Event::PaymentSent { payment_preimage } => {
6303 assert_eq!(payment_preimage, our_payment_preimage);
6305 _ => panic!("Unexpected event"),
6307 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)
6308 assert_eq!(node_txn.len(), 4);
6309 assert_eq!(node_txn[0], node_txn[3]);
6310 check_spends!(node_txn[0], commitment_tx[0].clone());
6311 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6312 assert_ne!(node_txn[0].lock_time, 0);
6313 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6314 check_spends!(node_txn[1], chan_1.3.clone());
6315 check_spends!(node_txn[2], node_txn[1].clone());
6316 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6317 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6318 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6319 assert_ne!(node_txn[2].lock_time, 0);
6323 fn test_htlc_on_chain_timeout() {
6324 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6325 // ChainWatchInterface and timeout the HTLC bacward accordingly. So here we test that ChannelManager is
6326 // broadcasting the right event to other nodes in payment path.
6327 // A ------------------> B ----------------------> C (timeout)
6328 // B's commitment tx C's commitment tx
6330 // B's HTLC timeout tx B's timeout tx
6332 let nodes = create_network(3);
6334 // Create some intial channels
6335 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6336 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6338 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6339 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6340 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6342 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6343 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6345 // Brodacast legit commitment tx from C on B's chain
6346 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6347 check_spends!(commitment_tx[0], chan_2.3.clone());
6348 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6350 let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6351 assert_eq!(added_monitors.len(), 1);
6352 added_monitors.clear();
6354 let events = nodes[2].node.get_and_clear_pending_msg_events();
6355 assert_eq!(events.len(), 1);
6357 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, .. } } => {
6358 assert!(update_add_htlcs.is_empty());
6359 assert!(!update_fail_htlcs.is_empty());
6360 assert!(update_fulfill_htlcs.is_empty());
6361 assert!(update_fail_malformed_htlcs.is_empty());
6362 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6364 _ => panic!("Unexpected event"),
6366 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6367 let events = nodes[2].node.get_and_clear_pending_msg_events();
6368 assert_eq!(events.len(), 1);
6370 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6371 _ => panic!("Unexpected event"),
6373 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6374 assert_eq!(node_txn.len(), 1);
6375 check_spends!(node_txn[0], chan_2.3.clone());
6376 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6378 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6379 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6380 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6383 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6384 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)
6385 assert_eq!(node_txn[0], node_txn[5]);
6386 assert_eq!(node_txn[1], node_txn[6]);
6387 assert_eq!(node_txn[2], node_txn[7]);
6388 check_spends!(node_txn[0], commitment_tx[0].clone());
6389 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6390 check_spends!(node_txn[1], chan_2.3.clone());
6391 check_spends!(node_txn[2], node_txn[1].clone());
6392 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6393 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6394 check_spends!(node_txn[3], chan_2.3.clone());
6395 check_spends!(node_txn[4], node_txn[3].clone());
6396 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6397 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6398 timeout_tx = node_txn[0].clone();
6402 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6403 let events = nodes[1].node.get_and_clear_pending_msg_events();
6404 check_added_monitors!(nodes[1], 1);
6405 assert_eq!(events.len(), 2);
6407 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6408 _ => panic!("Unexpected event"),
6411 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, .. } } => {
6412 assert!(update_add_htlcs.is_empty());
6413 assert!(!update_fail_htlcs.is_empty());
6414 assert!(update_fulfill_htlcs.is_empty());
6415 assert!(update_fail_malformed_htlcs.is_empty());
6416 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6418 _ => panic!("Unexpected event"),
6420 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
6421 assert_eq!(node_txn.len(), 0);
6423 // Broadcast legit commitment tx from B on A's chain
6424 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6425 check_spends!(commitment_tx[0], chan_1.3.clone());
6427 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6428 let events = nodes[0].node.get_and_clear_pending_msg_events();
6429 assert_eq!(events.len(), 1);
6431 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6432 _ => panic!("Unexpected event"),
6434 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
6435 assert_eq!(node_txn.len(), 4);
6436 assert_eq!(node_txn[0], node_txn[3]);
6437 check_spends!(node_txn[0], commitment_tx[0].clone());
6438 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6439 check_spends!(node_txn[1], chan_1.3.clone());
6440 check_spends!(node_txn[2], node_txn[1].clone());
6441 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6442 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6446 fn test_simple_commitment_revoked_fail_backward() {
6447 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6448 // and fail backward accordingly.
6450 let nodes = create_network(3);
6452 // Create some initial channels
6453 create_announced_chan_between_nodes(&nodes, 0, 1);
6454 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6456 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6457 // Get the will-be-revoked local txn from nodes[2]
6458 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6459 // Revoke the old state
6460 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6462 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6464 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6465 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6466 let events = nodes[1].node.get_and_clear_pending_msg_events();
6467 check_added_monitors!(nodes[1], 1);
6468 assert_eq!(events.len(), 2);
6470 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6471 _ => panic!("Unexpected event"),
6474 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, .. } } => {
6475 assert!(update_add_htlcs.is_empty());
6476 assert_eq!(update_fail_htlcs.len(), 1);
6477 assert!(update_fulfill_htlcs.is_empty());
6478 assert!(update_fail_malformed_htlcs.is_empty());
6479 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6481 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6482 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6484 let events = nodes[0].node.get_and_clear_pending_msg_events();
6485 assert_eq!(events.len(), 1);
6487 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6488 _ => panic!("Unexpected event"),
6490 let events = nodes[0].node.get_and_clear_pending_events();
6491 assert_eq!(events.len(), 1);
6493 Event::PaymentFailed { .. } => {},
6494 _ => panic!("Unexpected event"),
6497 _ => panic!("Unexpected event"),
6501 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6502 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6503 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6504 // commitment transaction anymore.
6505 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6506 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6507 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6508 // technically disallowed and we should probably handle it reasonably.
6509 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6510 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6512 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6513 // commitment_signed (implying it will be in the latest remote commitment transaction).
6514 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6515 // and once they revoke the previous commitment transaction (allowing us to send a new
6516 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6517 let mut nodes = create_network(3);
6519 // Create some initial channels
6520 create_announced_chan_between_nodes(&nodes, 0, 1);
6521 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6523 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6524 // Get the will-be-revoked local txn from nodes[2]
6525 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6526 // Revoke the old state
6527 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6529 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6530 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6531 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6533 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6534 check_added_monitors!(nodes[2], 1);
6535 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6536 assert!(updates.update_add_htlcs.is_empty());
6537 assert!(updates.update_fulfill_htlcs.is_empty());
6538 assert!(updates.update_fail_malformed_htlcs.is_empty());
6539 assert_eq!(updates.update_fail_htlcs.len(), 1);
6540 assert!(updates.update_fee.is_none());
6541 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6542 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6543 // Drop the last RAA from 3 -> 2
6545 assert!(nodes[2].node.fail_htlc_backwards(&second_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 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6555 check_added_monitors!(nodes[1], 1);
6556 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6557 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6558 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6559 check_added_monitors!(nodes[2], 1);
6561 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6562 check_added_monitors!(nodes[2], 1);
6563 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6564 assert!(updates.update_add_htlcs.is_empty());
6565 assert!(updates.update_fulfill_htlcs.is_empty());
6566 assert!(updates.update_fail_malformed_htlcs.is_empty());
6567 assert_eq!(updates.update_fail_htlcs.len(), 1);
6568 assert!(updates.update_fee.is_none());
6569 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6570 // At this point first_payment_hash has dropped out of the latest two commitment
6571 // transactions that nodes[1] is tracking...
6572 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6573 check_added_monitors!(nodes[1], 1);
6574 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6575 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6576 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6577 check_added_monitors!(nodes[2], 1);
6579 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6580 // on nodes[2]'s RAA.
6581 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6582 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6583 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6584 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6585 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6586 check_added_monitors!(nodes[1], 0);
6589 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6590 // One monitor for the new revocation preimage, one as we generate a commitment for
6591 // nodes[0] to fail first_payment_hash backwards.
6592 check_added_monitors!(nodes[1], 2);
6595 let mut failed_htlcs = HashSet::new();
6596 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6598 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6599 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6601 let events = nodes[1].node.get_and_clear_pending_events();
6602 assert_eq!(events.len(), 1);
6604 Event::PaymentFailed { ref payment_hash, .. } => {
6605 assert_eq!(*payment_hash, fourth_payment_hash);
6607 _ => panic!("Unexpected event"),
6610 if !deliver_bs_raa {
6611 // If we delivered the RAA already then we already failed first_payment_hash backwards.
6612 check_added_monitors!(nodes[1], 1);
6615 let events = nodes[1].node.get_and_clear_pending_msg_events();
6616 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6617 match events[if deliver_bs_raa { 2 } else { 0 }] {
6618 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6619 _ => panic!("Unexpected event"),
6623 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, .. } } => {
6624 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6625 assert_eq!(update_add_htlcs.len(), 1);
6626 assert!(update_fulfill_htlcs.is_empty());
6627 assert!(update_fail_htlcs.is_empty());
6628 assert!(update_fail_malformed_htlcs.is_empty());
6630 _ => panic!("Unexpected event"),
6633 // Due to the way backwards-failing occurs we do the updates in two steps.
6634 let updates = match events[1] {
6635 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, .. } } => {
6636 assert!(update_add_htlcs.is_empty());
6637 assert_eq!(update_fail_htlcs.len(), 1);
6638 assert!(update_fulfill_htlcs.is_empty());
6639 assert!(update_fail_malformed_htlcs.is_empty());
6640 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6642 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6643 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6644 check_added_monitors!(nodes[0], 1);
6645 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6646 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6647 check_added_monitors!(nodes[1], 1);
6648 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6649 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6650 check_added_monitors!(nodes[1], 1);
6651 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6652 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6653 check_added_monitors!(nodes[0], 1);
6655 if !deliver_bs_raa {
6656 // If we delievered B's RAA we got an unknown preimage error, not something
6657 // that we should update our routing table for.
6658 let events = nodes[0].node.get_and_clear_pending_msg_events();
6659 assert_eq!(events.len(), 1);
6661 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6662 _ => panic!("Unexpected event"),
6665 let events = nodes[0].node.get_and_clear_pending_events();
6666 assert_eq!(events.len(), 1);
6668 Event::PaymentFailed { ref payment_hash, .. } => {
6669 assert!(failed_htlcs.insert(payment_hash.0));
6671 _ => panic!("Unexpected event"),
6676 _ => panic!("Unexpected event"),
6679 assert!(updates.update_add_htlcs.is_empty());
6680 assert_eq!(updates.update_fail_htlcs.len(), 2);
6681 assert!(updates.update_fulfill_htlcs.is_empty());
6682 assert!(updates.update_fail_malformed_htlcs.is_empty());
6683 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6684 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6685 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6687 let events = nodes[0].node.get_and_clear_pending_msg_events();
6688 assert_eq!(events.len(), 2);
6689 for event in events {
6691 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6692 _ => panic!("Unexpected event"),
6696 let events = nodes[0].node.get_and_clear_pending_events();
6697 assert_eq!(events.len(), 2);
6699 Event::PaymentFailed { ref payment_hash, .. } => {
6700 assert!(failed_htlcs.insert(payment_hash.0));
6702 _ => panic!("Unexpected event"),
6705 Event::PaymentFailed { ref payment_hash, .. } => {
6706 assert!(failed_htlcs.insert(payment_hash.0));
6708 _ => panic!("Unexpected event"),
6711 assert!(failed_htlcs.contains(&first_payment_hash.0));
6712 assert!(failed_htlcs.contains(&second_payment_hash.0));
6713 assert!(failed_htlcs.contains(&third_payment_hash.0));
6717 fn test_commitment_revoked_fail_backward_exhaustive() {
6718 do_test_commitment_revoked_fail_backward_exhaustive(false);
6719 do_test_commitment_revoked_fail_backward_exhaustive(true);
6723 fn test_htlc_ignore_latest_remote_commitment() {
6724 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6725 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6726 let nodes = create_network(2);
6727 create_announced_chan_between_nodes(&nodes, 0, 1);
6729 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6730 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6732 let events = nodes[0].node.get_and_clear_pending_msg_events();
6733 assert_eq!(events.len(), 1);
6735 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6736 assert_eq!(flags & 0b10, 0b10);
6738 _ => panic!("Unexpected event"),
6742 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6743 assert_eq!(node_txn.len(), 2);
6745 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6746 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6749 let events = nodes[1].node.get_and_clear_pending_msg_events();
6750 assert_eq!(events.len(), 1);
6752 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6753 assert_eq!(flags & 0b10, 0b10);
6755 _ => panic!("Unexpected event"),
6759 // Duplicate the block_connected call since this may happen due to other listeners
6760 // registering new transactions
6761 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6765 fn test_force_close_fail_back() {
6766 // Check which HTLCs are failed-backwards on channel force-closure
6767 let mut nodes = create_network(3);
6768 create_announced_chan_between_nodes(&nodes, 0, 1);
6769 create_announced_chan_between_nodes(&nodes, 1, 2);
6771 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6773 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6775 let mut payment_event = {
6776 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6777 check_added_monitors!(nodes[0], 1);
6779 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6780 assert_eq!(events.len(), 1);
6781 SendEvent::from_event(events.remove(0))
6784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6785 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6787 let events_1 = nodes[1].node.get_and_clear_pending_events();
6788 assert_eq!(events_1.len(), 1);
6790 Event::PendingHTLCsForwardable { .. } => { },
6791 _ => panic!("Unexpected event"),
6794 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6795 nodes[1].node.process_pending_htlc_forwards();
6797 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6798 assert_eq!(events_2.len(), 1);
6799 payment_event = SendEvent::from_event(events_2.remove(0));
6800 assert_eq!(payment_event.msgs.len(), 1);
6802 check_added_monitors!(nodes[1], 1);
6803 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6804 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6805 check_added_monitors!(nodes[2], 1);
6806 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6808 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6809 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6810 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6812 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6813 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6814 assert_eq!(events_3.len(), 1);
6816 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6817 assert_eq!(flags & 0b10, 0b10);
6819 _ => panic!("Unexpected event"),
6823 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6824 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6825 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6826 // back to nodes[1] upon timeout otherwise.
6827 assert_eq!(node_txn.len(), 1);
6831 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6832 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6834 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6835 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6836 assert_eq!(events_4.len(), 1);
6838 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6839 assert_eq!(flags & 0b10, 0b10);
6841 _ => panic!("Unexpected event"),
6844 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6846 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6847 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6848 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6850 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6851 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6852 assert_eq!(node_txn.len(), 1);
6853 assert_eq!(node_txn[0].input.len(), 1);
6854 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6855 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6856 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6858 check_spends!(node_txn[0], tx);
6862 fn test_unconf_chan() {
6863 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6864 let nodes = create_network(2);
6865 create_announced_chan_between_nodes(&nodes, 0, 1);
6867 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6868 assert_eq!(channel_state.by_id.len(), 1);
6869 assert_eq!(channel_state.short_to_id.len(), 1);
6870 mem::drop(channel_state);
6872 let mut headers = Vec::new();
6873 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6874 headers.push(header.clone());
6876 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6877 headers.push(header.clone());
6879 while !headers.is_empty() {
6880 nodes[0].node.block_disconnected(&headers.pop().unwrap());
6883 let events = nodes[0].node.get_and_clear_pending_msg_events();
6884 assert_eq!(events.len(), 1);
6886 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6887 assert_eq!(flags & 0b10, 0b10);
6889 _ => panic!("Unexpected event"),
6892 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6893 assert_eq!(channel_state.by_id.len(), 0);
6894 assert_eq!(channel_state.short_to_id.len(), 0);
6897 macro_rules! get_chan_reestablish_msgs {
6898 ($src_node: expr, $dst_node: expr) => {
6900 let mut res = Vec::with_capacity(1);
6901 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6902 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6903 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6904 res.push(msg.clone());
6906 panic!("Unexpected event")
6914 macro_rules! handle_chan_reestablish_msgs {
6915 ($src_node: expr, $dst_node: expr) => {
6917 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6919 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6921 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6927 let mut revoke_and_ack = None;
6928 let mut commitment_update = None;
6929 let order = if let Some(ev) = msg_events.get(idx) {
6932 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6933 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6934 revoke_and_ack = Some(msg.clone());
6935 RAACommitmentOrder::RevokeAndACKFirst
6937 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6938 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6939 commitment_update = Some(updates.clone());
6940 RAACommitmentOrder::CommitmentFirst
6942 _ => panic!("Unexpected event"),
6945 RAACommitmentOrder::CommitmentFirst
6948 if let Some(ev) = msg_events.get(idx) {
6950 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6951 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6952 assert!(revoke_and_ack.is_none());
6953 revoke_and_ack = Some(msg.clone());
6955 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6956 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6957 assert!(commitment_update.is_none());
6958 commitment_update = Some(updates.clone());
6960 _ => panic!("Unexpected event"),
6964 (funding_locked, revoke_and_ack, commitment_update, order)
6969 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6970 /// for claims/fails they are separated out.
6971 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)) {
6972 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6973 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6974 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6975 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6977 if send_funding_locked.0 {
6978 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6980 for reestablish in reestablish_1.iter() {
6981 assert_eq!(reestablish.next_remote_commitment_number, 0);
6984 if send_funding_locked.1 {
6985 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6987 for reestablish in reestablish_2.iter() {
6988 assert_eq!(reestablish.next_remote_commitment_number, 0);
6991 if send_funding_locked.0 || send_funding_locked.1 {
6992 // If we expect any funding_locked's, both sides better have set
6993 // next_local_commitment_number to 1
6994 for reestablish in reestablish_1.iter() {
6995 assert_eq!(reestablish.next_local_commitment_number, 1);
6997 for reestablish in reestablish_2.iter() {
6998 assert_eq!(reestablish.next_local_commitment_number, 1);
7002 let mut resp_1 = Vec::new();
7003 for msg in reestablish_1 {
7004 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7005 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7007 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7008 check_added_monitors!(node_b, 1);
7010 check_added_monitors!(node_b, 0);
7013 let mut resp_2 = Vec::new();
7014 for msg in reestablish_2 {
7015 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7016 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7018 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7019 check_added_monitors!(node_a, 1);
7021 check_added_monitors!(node_a, 0);
7024 // We dont yet support both needing updates, as that would require a different commitment dance:
7025 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7026 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7028 for chan_msgs in resp_1.drain(..) {
7029 if send_funding_locked.0 {
7030 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7031 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7032 if !announcement_event.is_empty() {
7033 assert_eq!(announcement_event.len(), 1);
7034 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7035 //TODO: Test announcement_sigs re-sending
7036 } else { panic!("Unexpected event!"); }
7039 assert!(chan_msgs.0.is_none());
7042 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7043 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7044 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7045 check_added_monitors!(node_a, 1);
7047 assert!(chan_msgs.1.is_none());
7049 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7050 let commitment_update = chan_msgs.2.unwrap();
7051 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7052 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7054 assert!(commitment_update.update_add_htlcs.is_empty());
7056 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7057 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7058 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7059 for update_add in commitment_update.update_add_htlcs {
7060 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7062 for update_fulfill in commitment_update.update_fulfill_htlcs {
7063 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7065 for update_fail in commitment_update.update_fail_htlcs {
7066 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7069 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7070 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7072 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7073 check_added_monitors!(node_a, 1);
7074 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7075 // No commitment_signed so get_event_msg's assert(len == 1) passes
7076 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7077 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7078 check_added_monitors!(node_b, 1);
7081 assert!(chan_msgs.2.is_none());
7085 for chan_msgs in resp_2.drain(..) {
7086 if send_funding_locked.1 {
7087 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7088 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7089 if !announcement_event.is_empty() {
7090 assert_eq!(announcement_event.len(), 1);
7091 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7092 //TODO: Test announcement_sigs re-sending
7093 } else { panic!("Unexpected event!"); }
7096 assert!(chan_msgs.0.is_none());
7099 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7100 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7101 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7102 check_added_monitors!(node_b, 1);
7104 assert!(chan_msgs.1.is_none());
7106 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7107 let commitment_update = chan_msgs.2.unwrap();
7108 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7109 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7111 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7112 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7113 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7114 for update_add in commitment_update.update_add_htlcs {
7115 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7117 for update_fulfill in commitment_update.update_fulfill_htlcs {
7118 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7120 for update_fail in commitment_update.update_fail_htlcs {
7121 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7124 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7125 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7127 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7128 check_added_monitors!(node_b, 1);
7129 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7130 // No commitment_signed so get_event_msg's assert(len == 1) passes
7131 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7132 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7133 check_added_monitors!(node_a, 1);
7136 assert!(chan_msgs.2.is_none());
7142 fn test_simple_peer_disconnect() {
7143 // Test that we can reconnect when there are no lost messages
7144 let nodes = create_network(3);
7145 create_announced_chan_between_nodes(&nodes, 0, 1);
7146 create_announced_chan_between_nodes(&nodes, 1, 2);
7148 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7149 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7150 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7152 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7153 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7154 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7155 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7157 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7158 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7159 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7161 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7162 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7163 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7164 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7166 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7167 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7169 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7170 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7172 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7174 let events = nodes[0].node.get_and_clear_pending_events();
7175 assert_eq!(events.len(), 2);
7177 Event::PaymentSent { payment_preimage } => {
7178 assert_eq!(payment_preimage, payment_preimage_3);
7180 _ => panic!("Unexpected event"),
7183 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7184 assert_eq!(payment_hash, payment_hash_5);
7185 assert!(rejected_by_dest);
7187 _ => panic!("Unexpected event"),
7191 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7192 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7195 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7196 // Test that we can reconnect when in-flight HTLC updates get dropped
7197 let mut nodes = create_network(2);
7198 if messages_delivered == 0 {
7199 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7200 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7202 create_announced_chan_between_nodes(&nodes, 0, 1);
7205 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();
7206 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7208 let payment_event = {
7209 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7210 check_added_monitors!(nodes[0], 1);
7212 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7213 assert_eq!(events.len(), 1);
7214 SendEvent::from_event(events.remove(0))
7216 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7218 if messages_delivered < 2 {
7219 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7221 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7222 if messages_delivered >= 3 {
7223 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7224 check_added_monitors!(nodes[1], 1);
7225 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7227 if messages_delivered >= 4 {
7228 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7229 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7230 check_added_monitors!(nodes[0], 1);
7232 if messages_delivered >= 5 {
7233 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7234 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7235 // No commitment_signed so get_event_msg's assert(len == 1) passes
7236 check_added_monitors!(nodes[0], 1);
7238 if messages_delivered >= 6 {
7239 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7240 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7241 check_added_monitors!(nodes[1], 1);
7248 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7249 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7250 if messages_delivered < 3 {
7251 // Even if the funding_locked messages get exchanged, as long as nothing further was
7252 // received on either side, both sides will need to resend them.
7253 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7254 } else if messages_delivered == 3 {
7255 // nodes[0] still wants its RAA + commitment_signed
7256 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7257 } else if messages_delivered == 4 {
7258 // nodes[0] still wants its commitment_signed
7259 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7260 } else if messages_delivered == 5 {
7261 // nodes[1] still wants its final RAA
7262 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7263 } else if messages_delivered == 6 {
7264 // Everything was delivered...
7265 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7268 let events_1 = nodes[1].node.get_and_clear_pending_events();
7269 assert_eq!(events_1.len(), 1);
7271 Event::PendingHTLCsForwardable { .. } => { },
7272 _ => panic!("Unexpected event"),
7275 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7276 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7277 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7279 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7280 nodes[1].node.process_pending_htlc_forwards();
7282 let events_2 = nodes[1].node.get_and_clear_pending_events();
7283 assert_eq!(events_2.len(), 1);
7285 Event::PaymentReceived { ref payment_hash, amt } => {
7286 assert_eq!(payment_hash_1, *payment_hash);
7287 assert_eq!(amt, 1000000);
7289 _ => panic!("Unexpected event"),
7292 nodes[1].node.claim_funds(payment_preimage_1);
7293 check_added_monitors!(nodes[1], 1);
7295 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7296 assert_eq!(events_3.len(), 1);
7297 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7298 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7299 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7300 assert!(updates.update_add_htlcs.is_empty());
7301 assert!(updates.update_fail_htlcs.is_empty());
7302 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7303 assert!(updates.update_fail_malformed_htlcs.is_empty());
7304 assert!(updates.update_fee.is_none());
7305 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7307 _ => panic!("Unexpected event"),
7310 if messages_delivered >= 1 {
7311 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7313 let events_4 = nodes[0].node.get_and_clear_pending_events();
7314 assert_eq!(events_4.len(), 1);
7316 Event::PaymentSent { ref payment_preimage } => {
7317 assert_eq!(payment_preimage_1, *payment_preimage);
7319 _ => panic!("Unexpected event"),
7322 if messages_delivered >= 2 {
7323 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7324 check_added_monitors!(nodes[0], 1);
7325 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7327 if messages_delivered >= 3 {
7328 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7329 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7330 check_added_monitors!(nodes[1], 1);
7332 if messages_delivered >= 4 {
7333 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7334 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7335 // No commitment_signed so get_event_msg's assert(len == 1) passes
7336 check_added_monitors!(nodes[1], 1);
7338 if messages_delivered >= 5 {
7339 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7340 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7341 check_added_monitors!(nodes[0], 1);
7348 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7349 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7350 if messages_delivered < 2 {
7351 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7352 //TODO: Deduplicate PaymentSent events, then enable this if:
7353 //if messages_delivered < 1 {
7354 let events_4 = nodes[0].node.get_and_clear_pending_events();
7355 assert_eq!(events_4.len(), 1);
7357 Event::PaymentSent { ref payment_preimage } => {
7358 assert_eq!(payment_preimage_1, *payment_preimage);
7360 _ => panic!("Unexpected event"),
7363 } else if messages_delivered == 2 {
7364 // nodes[0] still wants its RAA + commitment_signed
7365 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7366 } else if messages_delivered == 3 {
7367 // nodes[0] still wants its commitment_signed
7368 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7369 } else if messages_delivered == 4 {
7370 // nodes[1] still wants its final RAA
7371 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7372 } else if messages_delivered == 5 {
7373 // Everything was delivered...
7374 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7377 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7378 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7379 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7381 // Channel should still work fine...
7382 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7383 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7387 fn test_drop_messages_peer_disconnect_a() {
7388 do_test_drop_messages_peer_disconnect(0);
7389 do_test_drop_messages_peer_disconnect(1);
7390 do_test_drop_messages_peer_disconnect(2);
7391 do_test_drop_messages_peer_disconnect(3);
7395 fn test_drop_messages_peer_disconnect_b() {
7396 do_test_drop_messages_peer_disconnect(4);
7397 do_test_drop_messages_peer_disconnect(5);
7398 do_test_drop_messages_peer_disconnect(6);
7402 fn test_funding_peer_disconnect() {
7403 // Test that we can lock in our funding tx while disconnected
7404 let nodes = create_network(2);
7405 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7407 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7408 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7410 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7411 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7412 assert_eq!(events_1.len(), 1);
7414 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7415 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7417 _ => panic!("Unexpected event"),
7420 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7422 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7423 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7425 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7426 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7427 assert_eq!(events_2.len(), 2);
7429 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7430 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7432 _ => panic!("Unexpected event"),
7435 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7436 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7438 _ => panic!("Unexpected event"),
7441 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7443 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7444 // rebroadcasting announcement_signatures upon reconnect.
7446 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();
7447 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7448 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7452 fn test_drop_messages_peer_disconnect_dual_htlc() {
7453 // Test that we can handle reconnecting when both sides of a channel have pending
7454 // commitment_updates when we disconnect.
7455 let mut nodes = create_network(2);
7456 create_announced_chan_between_nodes(&nodes, 0, 1);
7458 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7460 // Now try to send a second payment which will fail to send
7461 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7462 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7464 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7465 check_added_monitors!(nodes[0], 1);
7467 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7468 assert_eq!(events_1.len(), 1);
7470 MessageSendEvent::UpdateHTLCs { .. } => {},
7471 _ => panic!("Unexpected event"),
7474 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7475 check_added_monitors!(nodes[1], 1);
7477 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7478 assert_eq!(events_2.len(), 1);
7480 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 } } => {
7481 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7482 assert!(update_add_htlcs.is_empty());
7483 assert_eq!(update_fulfill_htlcs.len(), 1);
7484 assert!(update_fail_htlcs.is_empty());
7485 assert!(update_fail_malformed_htlcs.is_empty());
7486 assert!(update_fee.is_none());
7488 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7489 let events_3 = nodes[0].node.get_and_clear_pending_events();
7490 assert_eq!(events_3.len(), 1);
7492 Event::PaymentSent { ref payment_preimage } => {
7493 assert_eq!(*payment_preimage, payment_preimage_1);
7495 _ => panic!("Unexpected event"),
7498 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7499 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7500 // No commitment_signed so get_event_msg's assert(len == 1) passes
7501 check_added_monitors!(nodes[0], 1);
7503 _ => panic!("Unexpected event"),
7506 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7507 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7509 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7510 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7511 assert_eq!(reestablish_1.len(), 1);
7512 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7513 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7514 assert_eq!(reestablish_2.len(), 1);
7516 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7517 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7518 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7519 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7521 assert!(as_resp.0.is_none());
7522 assert!(bs_resp.0.is_none());
7524 assert!(bs_resp.1.is_none());
7525 assert!(bs_resp.2.is_none());
7527 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7529 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7530 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7531 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7532 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7533 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7534 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();
7535 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7536 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7537 // No commitment_signed so get_event_msg's assert(len == 1) passes
7538 check_added_monitors!(nodes[1], 1);
7540 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7541 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7542 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7543 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7544 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7545 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7546 assert!(bs_second_commitment_signed.update_fee.is_none());
7547 check_added_monitors!(nodes[1], 1);
7549 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7550 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7551 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7552 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7553 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7554 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7555 assert!(as_commitment_signed.update_fee.is_none());
7556 check_added_monitors!(nodes[0], 1);
7558 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7559 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7560 // No commitment_signed so get_event_msg's assert(len == 1) passes
7561 check_added_monitors!(nodes[0], 1);
7563 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7564 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7565 // No commitment_signed so get_event_msg's assert(len == 1) passes
7566 check_added_monitors!(nodes[1], 1);
7568 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7569 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7570 check_added_monitors!(nodes[1], 1);
7572 let events_4 = nodes[1].node.get_and_clear_pending_events();
7573 assert_eq!(events_4.len(), 1);
7575 Event::PendingHTLCsForwardable { .. } => { },
7576 _ => panic!("Unexpected event"),
7579 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7580 nodes[1].node.process_pending_htlc_forwards();
7582 let events_5 = nodes[1].node.get_and_clear_pending_events();
7583 assert_eq!(events_5.len(), 1);
7585 Event::PaymentReceived { ref payment_hash, amt: _ } => {
7586 assert_eq!(payment_hash_2, *payment_hash);
7588 _ => panic!("Unexpected event"),
7591 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7592 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7593 check_added_monitors!(nodes[0], 1);
7595 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7599 fn test_simple_monitor_permanent_update_fail() {
7600 // Test that we handle a simple permanent monitor update failure
7601 let mut nodes = create_network(2);
7602 create_announced_chan_between_nodes(&nodes, 0, 1);
7604 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7605 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7607 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7608 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7609 check_added_monitors!(nodes[0], 1);
7611 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7612 assert_eq!(events_1.len(), 2);
7614 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7615 _ => panic!("Unexpected event"),
7618 MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7619 _ => panic!("Unexpected event"),
7622 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7623 // PaymentFailed event
7625 assert_eq!(nodes[0].node.list_channels().len(), 0);
7628 fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7629 // Test that we can recover from a simple temporary monitor update failure optionally with
7630 // a disconnect in between
7631 let mut nodes = create_network(2);
7632 create_announced_chan_between_nodes(&nodes, 0, 1);
7634 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7635 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7637 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7638 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7639 check_added_monitors!(nodes[0], 1);
7641 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7642 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7643 assert_eq!(nodes[0].node.list_channels().len(), 1);
7646 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7647 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7648 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7651 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7652 nodes[0].node.test_restore_channel_monitor();
7653 check_added_monitors!(nodes[0], 1);
7655 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7656 assert_eq!(events_2.len(), 1);
7657 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7658 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7659 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7660 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7662 expect_pending_htlcs_forwardable!(nodes[1]);
7664 let events_3 = nodes[1].node.get_and_clear_pending_events();
7665 assert_eq!(events_3.len(), 1);
7667 Event::PaymentReceived { ref payment_hash, amt } => {
7668 assert_eq!(payment_hash_1, *payment_hash);
7669 assert_eq!(amt, 1000000);
7671 _ => panic!("Unexpected event"),
7674 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7676 // Now set it to failed again...
7677 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7678 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7679 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7680 check_added_monitors!(nodes[0], 1);
7682 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7683 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7684 assert_eq!(nodes[0].node.list_channels().len(), 1);
7687 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7688 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7689 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7692 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7693 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7694 nodes[0].node.test_restore_channel_monitor();
7695 check_added_monitors!(nodes[0], 1);
7697 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7698 assert_eq!(events_5.len(), 1);
7700 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7701 _ => panic!("Unexpected event"),
7704 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7705 // PaymentFailed event
7707 assert_eq!(nodes[0].node.list_channels().len(), 0);
7711 fn test_simple_monitor_temporary_update_fail() {
7712 do_test_simple_monitor_temporary_update_fail(false);
7713 do_test_simple_monitor_temporary_update_fail(true);
7716 fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7717 let disconnect_flags = 8 | 16;
7719 // Test that we can recover from a temporary monitor update failure with some in-flight
7720 // HTLCs going on at the same time potentially with some disconnection thrown in.
7721 // * First we route a payment, then get a temporary monitor update failure when trying to
7722 // route a second payment. We then claim the first payment.
7723 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7724 // TemporaryFailure likely indicates net disconnect which resulted in failing to update
7725 // the ChannelMonitor on a watchtower).
7726 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7727 // immediately, otherwise we wait sconnect and deliver them via the reconnect
7728 // channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7729 // disconnect_count & !disconnect_flags is 0).
7730 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7731 // through message sending, potentially disconnect/reconnecting multiple times based on
7732 // disconnect_count, to get the update_fulfill_htlc through.
7733 // * We then walk through more message exchanges to get the original update_add_htlc
7734 // through, swapping message ordering based on disconnect_count & 8 and optionally
7735 // disconnect/reconnecting based on disconnect_count.
7736 let mut nodes = create_network(2);
7737 create_announced_chan_between_nodes(&nodes, 0, 1);
7739 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7741 // Now try to send a second payment which will fail to send
7742 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7743 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7745 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7746 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7747 check_added_monitors!(nodes[0], 1);
7749 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7750 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7751 assert_eq!(nodes[0].node.list_channels().len(), 1);
7753 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7754 // but nodes[0] won't respond since it is frozen.
7755 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7756 check_added_monitors!(nodes[1], 1);
7757 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7758 assert_eq!(events_2.len(), 1);
7759 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7760 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 } } => {
7761 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7762 assert!(update_add_htlcs.is_empty());
7763 assert_eq!(update_fulfill_htlcs.len(), 1);
7764 assert!(update_fail_htlcs.is_empty());
7765 assert!(update_fail_malformed_htlcs.is_empty());
7766 assert!(update_fee.is_none());
7768 if (disconnect_count & 16) == 0 {
7769 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7770 let events_3 = nodes[0].node.get_and_clear_pending_events();
7771 assert_eq!(events_3.len(), 1);
7773 Event::PaymentSent { ref payment_preimage } => {
7774 assert_eq!(*payment_preimage, payment_preimage_1);
7776 _ => panic!("Unexpected event"),
7779 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) {
7780 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7781 } else { panic!(); }
7784 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7786 _ => panic!("Unexpected event"),
7789 if disconnect_count & !disconnect_flags > 0 {
7790 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7791 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7794 // Now fix monitor updating...
7795 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7796 nodes[0].node.test_restore_channel_monitor();
7797 check_added_monitors!(nodes[0], 1);
7799 macro_rules! disconnect_reconnect_peers { () => { {
7800 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7801 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7803 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7804 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7805 assert_eq!(reestablish_1.len(), 1);
7806 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7807 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7808 assert_eq!(reestablish_2.len(), 1);
7810 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7811 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7812 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7813 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7815 assert!(as_resp.0.is_none());
7816 assert!(bs_resp.0.is_none());
7818 (reestablish_1, reestablish_2, as_resp, bs_resp)
7821 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7822 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7823 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7825 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7826 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7827 assert_eq!(reestablish_1.len(), 1);
7828 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7829 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7830 assert_eq!(reestablish_2.len(), 1);
7832 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7833 check_added_monitors!(nodes[0], 0);
7834 let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7835 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7836 check_added_monitors!(nodes[1], 0);
7837 let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7839 assert!(as_resp.0.is_none());
7840 assert!(bs_resp.0.is_none());
7842 assert!(bs_resp.1.is_none());
7843 if (disconnect_count & 16) == 0 {
7844 assert!(bs_resp.2.is_none());
7846 assert!(as_resp.1.is_some());
7847 assert!(as_resp.2.is_some());
7848 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7850 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7851 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7852 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7853 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7854 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7855 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7857 assert!(as_resp.1.is_none());
7859 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();
7860 let events_3 = nodes[0].node.get_and_clear_pending_events();
7861 assert_eq!(events_3.len(), 1);
7863 Event::PaymentSent { ref payment_preimage } => {
7864 assert_eq!(*payment_preimage, payment_preimage_1);
7866 _ => panic!("Unexpected event"),
7869 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7870 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7871 // No commitment_signed so get_event_msg's assert(len == 1) passes
7872 check_added_monitors!(nodes[0], 1);
7874 as_resp.1 = Some(as_resp_raa);
7878 if disconnect_count & !disconnect_flags > 1 {
7879 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7881 if (disconnect_count & 16) == 0 {
7882 assert!(reestablish_1 == second_reestablish_1);
7883 assert!(reestablish_2 == second_reestablish_2);
7885 assert!(as_resp == second_as_resp);
7886 assert!(bs_resp == second_bs_resp);
7889 (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7891 let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7892 assert_eq!(events_4.len(), 2);
7893 (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7894 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7895 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7898 _ => panic!("Unexpected event"),
7902 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7904 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7906 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7907 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7908 check_added_monitors!(nodes[1], 1);
7910 if disconnect_count & !disconnect_flags > 2 {
7911 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7913 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7914 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7916 assert!(as_resp.2.is_none());
7917 assert!(bs_resp.2.is_none());
7920 let as_commitment_update;
7921 let bs_second_commitment_update;
7923 macro_rules! handle_bs_raa { () => {
7924 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7925 as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7926 assert!(as_commitment_update.update_add_htlcs.is_empty());
7927 assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7928 assert!(as_commitment_update.update_fail_htlcs.is_empty());
7929 assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7930 assert!(as_commitment_update.update_fee.is_none());
7931 check_added_monitors!(nodes[0], 1);
7934 macro_rules! handle_initial_raa { () => {
7935 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7936 bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7937 assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7938 assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7939 assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7940 assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7941 assert!(bs_second_commitment_update.update_fee.is_none());
7942 check_added_monitors!(nodes[1], 1);
7945 if (disconnect_count & 8) == 0 {
7948 if disconnect_count & !disconnect_flags > 3 {
7949 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7951 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7952 assert!(bs_resp.1.is_none());
7954 assert!(as_resp.2.unwrap() == as_commitment_update);
7955 assert!(bs_resp.2.is_none());
7957 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7960 handle_initial_raa!();
7962 if disconnect_count & !disconnect_flags > 4 {
7963 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7965 assert!(as_resp.1.is_none());
7966 assert!(bs_resp.1.is_none());
7968 assert!(as_resp.2.unwrap() == as_commitment_update);
7969 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7972 handle_initial_raa!();
7974 if disconnect_count & !disconnect_flags > 3 {
7975 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7977 assert!(as_resp.1.is_none());
7978 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7980 assert!(as_resp.2.is_none());
7981 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7983 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7988 if disconnect_count & !disconnect_flags > 4 {
7989 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7991 assert!(as_resp.1.is_none());
7992 assert!(bs_resp.1.is_none());
7994 assert!(as_resp.2.unwrap() == as_commitment_update);
7995 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7999 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
8000 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8001 // No commitment_signed so get_event_msg's assert(len == 1) passes
8002 check_added_monitors!(nodes[0], 1);
8004 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8005 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8006 // No commitment_signed so get_event_msg's assert(len == 1) passes
8007 check_added_monitors!(nodes[1], 1);
8009 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8010 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8011 check_added_monitors!(nodes[1], 1);
8013 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8014 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8015 check_added_monitors!(nodes[0], 1);
8017 expect_pending_htlcs_forwardable!(nodes[1]);
8019 let events_5 = nodes[1].node.get_and_clear_pending_events();
8020 assert_eq!(events_5.len(), 1);
8022 Event::PaymentReceived { ref payment_hash, amt } => {
8023 assert_eq!(payment_hash_2, *payment_hash);
8024 assert_eq!(amt, 1000000);
8026 _ => panic!("Unexpected event"),
8029 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8033 fn test_monitor_temporary_update_fail_a() {
8034 do_test_monitor_temporary_update_fail(0);
8035 do_test_monitor_temporary_update_fail(1);
8036 do_test_monitor_temporary_update_fail(2);
8037 do_test_monitor_temporary_update_fail(3);
8038 do_test_monitor_temporary_update_fail(4);
8039 do_test_monitor_temporary_update_fail(5);
8043 fn test_monitor_temporary_update_fail_b() {
8044 do_test_monitor_temporary_update_fail(2 | 8);
8045 do_test_monitor_temporary_update_fail(3 | 8);
8046 do_test_monitor_temporary_update_fail(4 | 8);
8047 do_test_monitor_temporary_update_fail(5 | 8);
8051 fn test_monitor_temporary_update_fail_c() {
8052 do_test_monitor_temporary_update_fail(1 | 16);
8053 do_test_monitor_temporary_update_fail(2 | 16);
8054 do_test_monitor_temporary_update_fail(3 | 16);
8055 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8056 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8060 fn test_monitor_update_fail_cs() {
8061 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8062 let mut nodes = create_network(2);
8063 create_announced_chan_between_nodes(&nodes, 0, 1);
8065 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8066 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8067 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8068 check_added_monitors!(nodes[0], 1);
8070 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8071 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8073 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8074 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() {
8075 assert_eq!(err, "Failed to update ChannelMonitor");
8076 } else { panic!(); }
8077 check_added_monitors!(nodes[1], 1);
8078 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8080 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8081 nodes[1].node.test_restore_channel_monitor();
8082 check_added_monitors!(nodes[1], 1);
8083 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8084 assert_eq!(responses.len(), 2);
8086 match responses[0] {
8087 MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8088 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8089 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8090 check_added_monitors!(nodes[0], 1);
8092 _ => panic!("Unexpected event"),
8094 match responses[1] {
8095 MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8096 assert!(updates.update_add_htlcs.is_empty());
8097 assert!(updates.update_fulfill_htlcs.is_empty());
8098 assert!(updates.update_fail_htlcs.is_empty());
8099 assert!(updates.update_fail_malformed_htlcs.is_empty());
8100 assert!(updates.update_fee.is_none());
8101 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8103 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8104 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() {
8105 assert_eq!(err, "Failed to update ChannelMonitor");
8106 } else { panic!(); }
8107 check_added_monitors!(nodes[0], 1);
8108 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8110 _ => panic!("Unexpected event"),
8113 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8114 nodes[0].node.test_restore_channel_monitor();
8115 check_added_monitors!(nodes[0], 1);
8117 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8118 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8119 check_added_monitors!(nodes[1], 1);
8121 let mut events = nodes[1].node.get_and_clear_pending_events();
8122 assert_eq!(events.len(), 1);
8124 Event::PendingHTLCsForwardable { .. } => { },
8125 _ => panic!("Unexpected event"),
8127 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8128 nodes[1].node.process_pending_htlc_forwards();
8130 events = nodes[1].node.get_and_clear_pending_events();
8131 assert_eq!(events.len(), 1);
8133 Event::PaymentReceived { payment_hash, amt } => {
8134 assert_eq!(payment_hash, our_payment_hash);
8135 assert_eq!(amt, 1000000);
8137 _ => panic!("Unexpected event"),
8140 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8143 fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8144 // Tests handling of a monitor update failure when processing an incoming RAA
8145 let mut nodes = create_network(3);
8146 create_announced_chan_between_nodes(&nodes, 0, 1);
8147 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8149 // Rebalance a bit so that we can send backwards from 2 to 1.
8150 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8152 // Route a first payment that we'll fail backwards
8153 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8155 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8156 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8157 check_added_monitors!(nodes[2], 1);
8159 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8160 assert!(updates.update_add_htlcs.is_empty());
8161 assert!(updates.update_fulfill_htlcs.is_empty());
8162 assert_eq!(updates.update_fail_htlcs.len(), 1);
8163 assert!(updates.update_fail_malformed_htlcs.is_empty());
8164 assert!(updates.update_fee.is_none());
8165 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8167 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8168 check_added_monitors!(nodes[0], 0);
8170 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8172 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8173 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8174 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8175 check_added_monitors!(nodes[0], 1);
8177 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8178 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8179 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8181 let events_1 = nodes[1].node.get_and_clear_pending_events();
8182 assert_eq!(events_1.len(), 1);
8184 Event::PendingHTLCsForwardable { .. } => { },
8185 _ => panic!("Unexpected event"),
8188 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8189 nodes[1].node.process_pending_htlc_forwards();
8190 check_added_monitors!(nodes[1], 0);
8191 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8193 // Now fail monitor updating.
8194 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8195 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() {
8196 assert_eq!(err, "Failed to update ChannelMonitor");
8197 } else { panic!(); }
8198 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8199 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8200 check_added_monitors!(nodes[1], 1);
8202 // Attempt to forward a third payment but fail due to the second channel being unavailable
8205 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8206 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8207 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8208 check_added_monitors!(nodes[0], 1);
8210 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8211 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8212 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8213 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8214 check_added_monitors!(nodes[1], 0);
8216 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8217 assert_eq!(events_2.len(), 1);
8218 match events_2.remove(0) {
8219 MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8220 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8221 assert!(updates.update_fulfill_htlcs.is_empty());
8222 assert_eq!(updates.update_fail_htlcs.len(), 1);
8223 assert!(updates.update_fail_malformed_htlcs.is_empty());
8224 assert!(updates.update_add_htlcs.is_empty());
8225 assert!(updates.update_fee.is_none());
8227 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8228 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8230 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8231 assert_eq!(msg_events.len(), 1);
8232 match msg_events[0] {
8233 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8234 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8235 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8237 _ => panic!("Unexpected event"),
8240 let events = nodes[0].node.get_and_clear_pending_events();
8241 assert_eq!(events.len(), 1);
8242 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8243 assert_eq!(payment_hash, payment_hash_3);
8244 assert!(!rejected_by_dest);
8245 } else { panic!("Unexpected event!"); }
8247 _ => panic!("Unexpected event type!"),
8250 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8251 // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8252 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8253 let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8254 nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8255 check_added_monitors!(nodes[2], 1);
8257 send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8258 nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8259 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) {
8260 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8261 } else { panic!(); }
8262 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8263 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8264 (Some(payment_preimage_4), Some(payment_hash_4))
8265 } else { (None, None) };
8267 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8268 // update_add update.
8269 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8270 nodes[1].node.test_restore_channel_monitor();
8271 check_added_monitors!(nodes[1], 2);
8273 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8274 if test_ignore_second_cs {
8275 assert_eq!(events_3.len(), 3);
8277 assert_eq!(events_3.len(), 2);
8280 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8281 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8282 let messages_a = match events_3.pop().unwrap() {
8283 MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8284 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8285 assert!(updates.update_fulfill_htlcs.is_empty());
8286 assert_eq!(updates.update_fail_htlcs.len(), 1);
8287 assert!(updates.update_fail_malformed_htlcs.is_empty());
8288 assert!(updates.update_add_htlcs.is_empty());
8289 assert!(updates.update_fee.is_none());
8290 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8292 _ => panic!("Unexpected event type!"),
8294 let raa = if test_ignore_second_cs {
8295 match events_3.remove(1) {
8296 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8297 assert_eq!(node_id, nodes[2].node.get_our_node_id());
8300 _ => panic!("Unexpected event"),
8303 let send_event_b = SendEvent::from_event(events_3.remove(0));
8304 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8306 // Now deliver the new messages...
8308 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8309 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8310 let events_4 = nodes[0].node.get_and_clear_pending_events();
8311 assert_eq!(events_4.len(), 1);
8312 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8313 assert_eq!(payment_hash, payment_hash_1);
8314 assert!(rejected_by_dest);
8315 } else { panic!("Unexpected event!"); }
8317 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8318 if test_ignore_second_cs {
8319 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8320 check_added_monitors!(nodes[2], 1);
8321 let bs_revoke_and_ack = 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(), &raa.unwrap()).unwrap();
8323 check_added_monitors!(nodes[2], 1);
8324 let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8325 assert!(bs_cs.update_add_htlcs.is_empty());
8326 assert!(bs_cs.update_fail_htlcs.is_empty());
8327 assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8328 assert!(bs_cs.update_fulfill_htlcs.is_empty());
8329 assert!(bs_cs.update_fee.is_none());
8331 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8332 check_added_monitors!(nodes[1], 1);
8333 let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8334 assert!(as_cs.update_add_htlcs.is_empty());
8335 assert!(as_cs.update_fail_htlcs.is_empty());
8336 assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8337 assert!(as_cs.update_fulfill_htlcs.is_empty());
8338 assert!(as_cs.update_fee.is_none());
8340 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8341 check_added_monitors!(nodes[1], 1);
8342 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8344 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8345 check_added_monitors!(nodes[2], 1);
8346 let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8348 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8349 check_added_monitors!(nodes[2], 1);
8350 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8352 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8353 check_added_monitors!(nodes[1], 1);
8354 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8356 commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8359 let events_5 = nodes[2].node.get_and_clear_pending_events();
8360 assert_eq!(events_5.len(), 1);
8362 Event::PendingHTLCsForwardable { .. } => { },
8363 _ => panic!("Unexpected event"),
8366 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8367 nodes[2].node.process_pending_htlc_forwards();
8369 let events_6 = nodes[2].node.get_and_clear_pending_events();
8370 assert_eq!(events_6.len(), 1);
8372 Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8373 _ => panic!("Unexpected event"),
8376 if test_ignore_second_cs {
8377 let events_7 = nodes[1].node.get_and_clear_pending_events();
8378 assert_eq!(events_7.len(), 1);
8380 Event::PendingHTLCsForwardable { .. } => { },
8381 _ => panic!("Unexpected event"),
8384 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8385 nodes[1].node.process_pending_htlc_forwards();
8386 check_added_monitors!(nodes[1], 1);
8388 send_event = SendEvent::from_node(&nodes[1]);
8389 assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8390 assert_eq!(send_event.msgs.len(), 1);
8391 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8392 commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8394 let events_8 = nodes[0].node.get_and_clear_pending_events();
8395 assert_eq!(events_8.len(), 1);
8397 Event::PendingHTLCsForwardable { .. } => { },
8398 _ => panic!("Unexpected event"),
8401 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8402 nodes[0].node.process_pending_htlc_forwards();
8404 let events_9 = nodes[0].node.get_and_clear_pending_events();
8405 assert_eq!(events_9.len(), 1);
8407 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8408 _ => panic!("Unexpected event"),
8410 claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8413 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8417 fn test_monitor_update_fail_raa() {
8418 do_test_monitor_update_fail_raa(false);
8419 do_test_monitor_update_fail_raa(true);
8423 fn test_monitor_update_fail_reestablish() {
8424 // Simple test for message retransmission after monitor update failure on
8425 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8427 let mut nodes = create_network(3);
8428 create_announced_chan_between_nodes(&nodes, 0, 1);
8429 create_announced_chan_between_nodes(&nodes, 1, 2);
8431 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8433 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8434 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8436 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8437 check_added_monitors!(nodes[2], 1);
8438 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8439 assert!(updates.update_add_htlcs.is_empty());
8440 assert!(updates.update_fail_htlcs.is_empty());
8441 assert!(updates.update_fail_malformed_htlcs.is_empty());
8442 assert!(updates.update_fee.is_none());
8443 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8444 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8445 check_added_monitors!(nodes[1], 1);
8446 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8447 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8449 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8450 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8451 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8453 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8454 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8456 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8458 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() {
8459 assert_eq!(err, "Failed to update ChannelMonitor");
8460 } else { panic!(); }
8461 check_added_monitors!(nodes[1], 1);
8463 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8464 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8466 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8467 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8469 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8470 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8472 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8474 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8475 check_added_monitors!(nodes[1], 0);
8476 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8478 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8479 nodes[1].node.test_restore_channel_monitor();
8480 check_added_monitors!(nodes[1], 1);
8482 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8483 assert!(updates.update_add_htlcs.is_empty());
8484 assert!(updates.update_fail_htlcs.is_empty());
8485 assert!(updates.update_fail_malformed_htlcs.is_empty());
8486 assert!(updates.update_fee.is_none());
8487 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8488 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8489 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8491 let events = nodes[0].node.get_and_clear_pending_events();
8492 assert_eq!(events.len(), 1);
8494 Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8495 _ => panic!("Unexpected event"),
8500 fn test_invalid_channel_announcement() {
8501 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8502 let secp_ctx = Secp256k1::new();
8503 let nodes = create_network(2);
8505 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8507 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8508 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8509 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8510 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8512 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 } );
8514 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8515 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8517 let as_network_key = nodes[0].node.get_our_node_id();
8518 let bs_network_key = nodes[1].node.get_our_node_id();
8520 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8522 let mut chan_announcement;
8524 macro_rules! dummy_unsigned_msg {
8526 msgs::UnsignedChannelAnnouncement {
8527 features: msgs::GlobalFeatures::new(),
8528 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8529 short_channel_id: as_chan.get_short_channel_id().unwrap(),
8530 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8531 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8532 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8533 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8534 excess_data: Vec::new(),
8539 macro_rules! sign_msg {
8540 ($unsigned_msg: expr) => {
8541 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8542 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8543 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8544 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8545 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8546 chan_announcement = msgs::ChannelAnnouncement {
8547 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8548 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8549 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8550 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8551 contents: $unsigned_msg
8556 let unsigned_msg = dummy_unsigned_msg!();
8557 sign_msg!(unsigned_msg);
8558 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8559 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 } );
8561 // Configured with Network::Testnet
8562 let mut unsigned_msg = dummy_unsigned_msg!();
8563 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8564 sign_msg!(unsigned_msg);
8565 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8567 let mut unsigned_msg = dummy_unsigned_msg!();
8568 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8569 sign_msg!(unsigned_msg);
8570 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8573 struct VecWriter(Vec<u8>);
8574 impl Writer for VecWriter {
8575 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8576 self.0.extend_from_slice(buf);
8579 fn size_hint(&mut self, size: usize) {
8580 self.0.reserve_exact(size);
8585 fn test_no_txn_manager_serialize_deserialize() {
8586 let mut nodes = create_network(2);
8588 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8592 let nodes_0_serialized = nodes[0].node.encode();
8593 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8594 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8596 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())));
8597 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8598 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8599 assert!(chan_0_monitor_read.is_empty());
8601 let mut nodes_0_read = &nodes_0_serialized[..];
8602 let config = UserConfig::new();
8603 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8604 let (_, nodes_0_deserialized) = {
8605 let mut channel_monitors = HashMap::new();
8606 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8607 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8608 default_config: config,
8610 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8611 monitor: nodes[0].chan_monitor.clone(),
8612 chain_monitor: nodes[0].chain_monitor.clone(),
8613 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8614 logger: Arc::new(test_utils::TestLogger::new()),
8615 channel_monitors: &channel_monitors,
8618 assert!(nodes_0_read.is_empty());
8620 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8621 nodes[0].node = Arc::new(nodes_0_deserialized);
8622 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8623 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8624 assert_eq!(nodes[0].node.list_channels().len(), 1);
8625 check_added_monitors!(nodes[0], 1);
8627 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8628 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8629 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8630 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8632 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8633 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8634 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8635 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8637 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8638 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8639 for node in nodes.iter() {
8640 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8641 node.router.handle_channel_update(&as_update).unwrap();
8642 node.router.handle_channel_update(&bs_update).unwrap();
8645 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8649 fn test_simple_manager_serialize_deserialize() {
8650 let mut nodes = create_network(2);
8651 create_announced_chan_between_nodes(&nodes, 0, 1);
8653 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8654 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8656 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8658 let nodes_0_serialized = nodes[0].node.encode();
8659 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8660 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8662 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())));
8663 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8664 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8665 assert!(chan_0_monitor_read.is_empty());
8667 let mut nodes_0_read = &nodes_0_serialized[..];
8668 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8669 let (_, nodes_0_deserialized) = {
8670 let mut channel_monitors = HashMap::new();
8671 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8672 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8673 default_config: UserConfig::new(),
8675 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8676 monitor: nodes[0].chan_monitor.clone(),
8677 chain_monitor: nodes[0].chain_monitor.clone(),
8678 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8679 logger: Arc::new(test_utils::TestLogger::new()),
8680 channel_monitors: &channel_monitors,
8683 assert!(nodes_0_read.is_empty());
8685 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8686 nodes[0].node = Arc::new(nodes_0_deserialized);
8687 check_added_monitors!(nodes[0], 1);
8689 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8691 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8692 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8696 fn test_manager_serialize_deserialize_inconsistent_monitor() {
8697 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8698 let mut nodes = create_network(4);
8699 create_announced_chan_between_nodes(&nodes, 0, 1);
8700 create_announced_chan_between_nodes(&nodes, 2, 0);
8701 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8703 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8705 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8706 let nodes_0_serialized = nodes[0].node.encode();
8708 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8709 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8710 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8711 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8713 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8715 let mut node_0_monitors_serialized = Vec::new();
8716 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8717 let mut writer = VecWriter(Vec::new());
8718 monitor.1.write_for_disk(&mut writer).unwrap();
8719 node_0_monitors_serialized.push(writer.0);
8722 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())));
8723 let mut node_0_monitors = Vec::new();
8724 for serialized in node_0_monitors_serialized.iter() {
8725 let mut read = &serialized[..];
8726 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8727 assert!(read.is_empty());
8728 node_0_monitors.push(monitor);
8731 let mut nodes_0_read = &nodes_0_serialized[..];
8732 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8733 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8734 default_config: UserConfig::new(),
8736 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8737 monitor: nodes[0].chan_monitor.clone(),
8738 chain_monitor: nodes[0].chain_monitor.clone(),
8739 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8740 logger: Arc::new(test_utils::TestLogger::new()),
8741 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8743 assert!(nodes_0_read.is_empty());
8745 { // Channel close should result in a commitment tx and an HTLC tx
8746 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8747 assert_eq!(txn.len(), 2);
8748 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8749 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8752 for monitor in node_0_monitors.drain(..) {
8753 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8754 check_added_monitors!(nodes[0], 1);
8756 nodes[0].node = Arc::new(nodes_0_deserialized);
8758 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8759 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8760 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8761 //... and we can even still claim the payment!
8762 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8764 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8765 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8766 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8767 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) {
8768 assert_eq!(msg.channel_id, channel_id);
8769 } else { panic!("Unexpected result"); }
8772 macro_rules! check_spendable_outputs {
8773 ($node: expr, $der_idx: expr) => {
8775 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8776 let mut txn = Vec::new();
8777 for event in events {
8779 Event::SpendableOutputs { ref outputs } => {
8780 for outp in outputs {
8782 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8784 previous_output: outpoint.clone(),
8785 script_sig: Script::new(),
8787 witness: Vec::new(),
8790 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8791 value: output.value,
8793 let mut spend_tx = Transaction {
8799 let secp_ctx = Secp256k1::new();
8800 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8801 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8802 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8803 let remotesig = secp_ctx.sign(&sighash, key);
8804 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8805 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8806 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8809 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8811 previous_output: outpoint.clone(),
8812 script_sig: Script::new(),
8813 sequence: *to_self_delay as u32,
8814 witness: Vec::new(),
8817 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8818 value: output.value,
8820 let mut spend_tx = Transaction {
8826 let secp_ctx = Secp256k1::new();
8827 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8828 let local_delaysig = secp_ctx.sign(&sighash, key);
8829 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8830 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8831 spend_tx.input[0].witness.push(vec!(0));
8832 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8835 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8836 let secp_ctx = Secp256k1::new();
8838 previous_output: outpoint.clone(),
8839 script_sig: Script::new(),
8841 witness: Vec::new(),
8844 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8845 value: output.value,
8847 let mut spend_tx = Transaction {
8851 output: vec![outp.clone()],
8854 match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8856 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8858 Err(_) => panic!("Your RNG is busted"),
8861 Err(_) => panic!("Your rng is busted"),
8864 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8865 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8866 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8867 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8868 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8869 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8870 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8876 _ => panic!("Unexpected event"),
8885 fn test_claim_sizeable_push_msat() {
8886 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8887 let nodes = create_network(2);
8889 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8890 nodes[1].node.force_close_channel(&chan.2);
8891 let events = nodes[1].node.get_and_clear_pending_msg_events();
8893 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8894 _ => panic!("Unexpected event"),
8896 let node_txn = nodes[1].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 spend_txn = check_spendable_outputs!(nodes[1], 1);
8904 assert_eq!(spend_txn.len(), 1);
8905 check_spends!(spend_txn[0], node_txn[0].clone());
8909 fn test_claim_on_remote_sizeable_push_msat() {
8910 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8911 // to_remote output is encumbered by a P2WPKH
8913 let nodes = create_network(2);
8915 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8916 nodes[0].node.force_close_channel(&chan.2);
8917 let events = nodes[0].node.get_and_clear_pending_msg_events();
8919 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8920 _ => panic!("Unexpected event"),
8922 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8923 assert_eq!(node_txn.len(), 1);
8924 check_spends!(node_txn[0], chan.3.clone());
8925 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
8927 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8928 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8929 let events = nodes[1].node.get_and_clear_pending_msg_events();
8931 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8932 _ => panic!("Unexpected event"),
8934 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8935 assert_eq!(spend_txn.len(), 2);
8936 assert_eq!(spend_txn[0], spend_txn[1]);
8937 check_spends!(spend_txn[0], node_txn[0].clone());
8941 fn test_claim_on_remote_revoked_sizeable_push_msat() {
8942 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8943 // to_remote output is encumbered by a P2WPKH
8945 let nodes = create_network(2);
8947 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8948 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8949 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8950 assert_eq!(revoked_local_txn[0].input.len(), 1);
8951 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8953 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8954 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8955 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8956 let events = nodes[1].node.get_and_clear_pending_msg_events();
8958 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8959 _ => panic!("Unexpected event"),
8961 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8962 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8963 assert_eq!(spend_txn.len(), 4);
8964 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8965 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8966 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8967 check_spends!(spend_txn[1], node_txn[0].clone());
8971 fn test_static_spendable_outputs_preimage_tx() {
8972 let nodes = create_network(2);
8974 // Create some initial channels
8975 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8977 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8979 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8980 assert_eq!(commitment_tx[0].input.len(), 1);
8981 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8983 // Settle A's commitment tx on B's chain
8984 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8985 assert!(nodes[1].node.claim_funds(payment_preimage));
8986 check_added_monitors!(nodes[1], 1);
8987 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8988 let events = nodes[1].node.get_and_clear_pending_msg_events();
8990 MessageSendEvent::UpdateHTLCs { .. } => {},
8991 _ => panic!("Unexpected event"),
8994 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8995 _ => panic!("Unexepected event"),
8998 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8999 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
9000 check_spends!(node_txn[0], commitment_tx[0].clone());
9001 assert_eq!(node_txn[0], node_txn[2]);
9002 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9003 check_spends!(node_txn[1], chan_1.3.clone());
9005 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
9006 assert_eq!(spend_txn.len(), 2);
9007 assert_eq!(spend_txn[0], spend_txn[1]);
9008 check_spends!(spend_txn[0], node_txn[0].clone());
9012 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
9013 let nodes = create_network(2);
9015 // Create some initial channels
9016 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9018 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9019 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9020 assert_eq!(revoked_local_txn[0].input.len(), 1);
9021 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9023 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9025 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9026 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9027 let events = nodes[1].node.get_and_clear_pending_msg_events();
9029 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9030 _ => panic!("Unexpected event"),
9032 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9033 assert_eq!(node_txn.len(), 3);
9034 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9035 assert_eq!(node_txn[0].input.len(), 2);
9036 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9038 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9039 assert_eq!(spend_txn.len(), 2);
9040 assert_eq!(spend_txn[0], spend_txn[1]);
9041 check_spends!(spend_txn[0], node_txn[0].clone());
9045 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9046 let nodes = create_network(2);
9048 // Create some initial channels
9049 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9051 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9052 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9053 assert_eq!(revoked_local_txn[0].input.len(), 1);
9054 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9056 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9058 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9059 // A will generate HTLC-Timeout from revoked commitment tx
9060 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9061 let events = nodes[0].node.get_and_clear_pending_msg_events();
9063 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9064 _ => panic!("Unexpected event"),
9066 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9067 assert_eq!(revoked_htlc_txn.len(), 3);
9068 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9069 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9070 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9071 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9072 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9074 // B will generate justice tx from A's revoked commitment/HTLC tx
9075 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9076 let events = nodes[1].node.get_and_clear_pending_msg_events();
9078 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9079 _ => panic!("Unexpected event"),
9082 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9083 assert_eq!(node_txn.len(), 4);
9084 assert_eq!(node_txn[3].input.len(), 1);
9085 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9087 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9088 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9089 assert_eq!(spend_txn.len(), 3);
9090 assert_eq!(spend_txn[0], spend_txn[1]);
9091 check_spends!(spend_txn[0], node_txn[0].clone());
9092 check_spends!(spend_txn[2], node_txn[3].clone());
9096 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9097 let nodes = create_network(2);
9099 // Create some initial channels
9100 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9102 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9103 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9104 assert_eq!(revoked_local_txn[0].input.len(), 1);
9105 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9107 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9109 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9110 // B will generate HTLC-Success from revoked commitment tx
9111 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9112 let events = nodes[1].node.get_and_clear_pending_msg_events();
9114 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9115 _ => panic!("Unexpected event"),
9117 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9119 assert_eq!(revoked_htlc_txn.len(), 3);
9120 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9121 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9122 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9123 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9125 // A will generate justice tx from B's revoked commitment/HTLC tx
9126 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9127 let events = nodes[0].node.get_and_clear_pending_msg_events();
9129 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9130 _ => panic!("Unexpected event"),
9133 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9134 assert_eq!(node_txn.len(), 4);
9135 assert_eq!(node_txn[3].input.len(), 1);
9136 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9138 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9139 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9140 assert_eq!(spend_txn.len(), 5);
9141 assert_eq!(spend_txn[0], spend_txn[2]);
9142 assert_eq!(spend_txn[1], spend_txn[3]);
9143 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9144 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9145 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9149 fn test_onchain_to_onchain_claim() {
9150 // Test that in case of channel closure, we detect the state of output thanks to
9151 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9152 // First, have C claim an HTLC against its own latest commitment transaction.
9153 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9155 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9158 let nodes = create_network(3);
9160 // Create some initial channels
9161 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9162 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9164 // Rebalance the network a bit by relaying one payment through all the channels ...
9165 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9166 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9168 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9169 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9170 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9171 check_spends!(commitment_tx[0], chan_2.3.clone());
9172 nodes[2].node.claim_funds(payment_preimage);
9173 check_added_monitors!(nodes[2], 1);
9174 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9175 assert!(updates.update_add_htlcs.is_empty());
9176 assert!(updates.update_fail_htlcs.is_empty());
9177 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9178 assert!(updates.update_fail_malformed_htlcs.is_empty());
9180 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9181 let events = nodes[2].node.get_and_clear_pending_msg_events();
9182 assert_eq!(events.len(), 1);
9184 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9185 _ => panic!("Unexpected event"),
9188 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9189 assert_eq!(c_txn.len(), 3);
9190 assert_eq!(c_txn[0], c_txn[2]);
9191 assert_eq!(commitment_tx[0], c_txn[1]);
9192 check_spends!(c_txn[1], chan_2.3.clone());
9193 check_spends!(c_txn[2], c_txn[1].clone());
9194 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9195 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9196 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9197 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9199 // 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
9200 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9202 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9203 assert_eq!(b_txn.len(), 4);
9204 assert_eq!(b_txn[0], b_txn[3]);
9205 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9206 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9207 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9208 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9209 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9210 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9211 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9212 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9213 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9216 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9217 check_added_monitors!(nodes[1], 1);
9218 match msg_events[0] {
9219 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9220 _ => panic!("Unexpected event"),
9222 match msg_events[1] {
9223 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, .. } } => {
9224 assert!(update_add_htlcs.is_empty());
9225 assert!(update_fail_htlcs.is_empty());
9226 assert_eq!(update_fulfill_htlcs.len(), 1);
9227 assert!(update_fail_malformed_htlcs.is_empty());
9228 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9230 _ => panic!("Unexpected event"),
9232 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9233 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9234 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9235 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9236 assert_eq!(b_txn.len(), 3);
9237 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9238 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9239 check_spends!(b_txn[0], commitment_tx[0].clone());
9240 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9241 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9242 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9243 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9244 match msg_events[0] {
9245 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9246 _ => panic!("Unexpected event"),
9251 fn test_duplicate_payment_hash_one_failure_one_success() {
9252 // Topology : A --> B --> C
9253 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9254 let mut nodes = create_network(3);
9256 create_announced_chan_between_nodes(&nodes, 0, 1);
9257 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9259 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9260 *nodes[0].network_payment_count.borrow_mut() -= 1;
9261 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9263 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9264 assert_eq!(commitment_txn[0].input.len(), 1);
9265 check_spends!(commitment_txn[0], chan_2.3.clone());
9267 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9268 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9269 let htlc_timeout_tx;
9270 { // Extract one of the two HTLC-Timeout transaction
9271 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9272 assert_eq!(node_txn.len(), 7);
9273 assert_eq!(node_txn[0], node_txn[5]);
9274 assert_eq!(node_txn[1], node_txn[6]);
9275 check_spends!(node_txn[0], commitment_txn[0].clone());
9276 assert_eq!(node_txn[0].input.len(), 1);
9277 check_spends!(node_txn[1], commitment_txn[0].clone());
9278 assert_eq!(node_txn[1].input.len(), 1);
9279 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9280 check_spends!(node_txn[2], chan_2.3.clone());
9281 check_spends!(node_txn[3], node_txn[2].clone());
9282 check_spends!(node_txn[4], node_txn[2].clone());
9283 htlc_timeout_tx = node_txn[1].clone();
9286 let events = nodes[1].node.get_and_clear_pending_msg_events();
9288 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9289 _ => panic!("Unexepected event"),
9292 nodes[2].node.claim_funds(our_payment_preimage);
9293 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9294 check_added_monitors!(nodes[2], 2);
9295 let events = nodes[2].node.get_and_clear_pending_msg_events();
9297 MessageSendEvent::UpdateHTLCs { .. } => {},
9298 _ => panic!("Unexpected event"),
9301 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9302 _ => panic!("Unexepected event"),
9304 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9305 assert_eq!(htlc_success_txn.len(), 5);
9306 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9307 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9308 assert_eq!(htlc_success_txn[0].input.len(), 1);
9309 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9310 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9311 assert_eq!(htlc_success_txn[1].input.len(), 1);
9312 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9313 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9314 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9315 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9317 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9318 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9319 assert!(htlc_updates.update_add_htlcs.is_empty());
9320 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9321 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9322 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9323 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9324 check_added_monitors!(nodes[1], 1);
9326 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9327 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9329 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9330 let events = nodes[0].node.get_and_clear_pending_msg_events();
9331 assert_eq!(events.len(), 1);
9333 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
9335 _ => { panic!("Unexpected event"); }
9338 let events = nodes[0].node.get_and_clear_pending_events();
9340 Event::PaymentFailed { ref payment_hash, .. } => {
9341 assert_eq!(*payment_hash, duplicate_payment_hash);
9343 _ => panic!("Unexpected event"),
9346 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9347 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9348 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9349 assert!(updates.update_add_htlcs.is_empty());
9350 assert!(updates.update_fail_htlcs.is_empty());
9351 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9352 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9353 assert!(updates.update_fail_malformed_htlcs.is_empty());
9354 check_added_monitors!(nodes[1], 1);
9356 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9357 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9359 let events = nodes[0].node.get_and_clear_pending_events();
9361 Event::PaymentSent { ref payment_preimage } => {
9362 assert_eq!(*payment_preimage, our_payment_preimage);
9364 _ => panic!("Unexpected event"),
9369 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9370 let nodes = create_network(2);
9372 // Create some initial channels
9373 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9375 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9376 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9377 assert_eq!(local_txn[0].input.len(), 1);
9378 check_spends!(local_txn[0], chan_1.3.clone());
9380 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9381 nodes[1].node.claim_funds(payment_preimage);
9382 check_added_monitors!(nodes[1], 1);
9383 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9384 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9385 let events = nodes[1].node.get_and_clear_pending_msg_events();
9387 MessageSendEvent::UpdateHTLCs { .. } => {},
9388 _ => panic!("Unexpected event"),
9391 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9392 _ => panic!("Unexepected event"),
9394 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9395 assert_eq!(node_txn[0].input.len(), 1);
9396 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9397 check_spends!(node_txn[0], local_txn[0].clone());
9399 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9400 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9401 assert_eq!(spend_txn.len(), 2);
9402 check_spends!(spend_txn[0], node_txn[0].clone());
9403 check_spends!(spend_txn[1], node_txn[2].clone());
9407 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9408 let nodes = create_network(2);
9410 // Create some initial channels
9411 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9413 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9414 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9415 assert_eq!(local_txn[0].input.len(), 1);
9416 check_spends!(local_txn[0], chan_1.3.clone());
9418 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9419 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9420 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9421 let events = nodes[0].node.get_and_clear_pending_msg_events();
9423 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9424 _ => panic!("Unexepected event"),
9426 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9427 assert_eq!(node_txn[0].input.len(), 1);
9428 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9429 check_spends!(node_txn[0], local_txn[0].clone());
9431 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9432 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9433 assert_eq!(spend_txn.len(), 8);
9434 assert_eq!(spend_txn[0], spend_txn[2]);
9435 assert_eq!(spend_txn[0], spend_txn[4]);
9436 assert_eq!(spend_txn[0], spend_txn[6]);
9437 assert_eq!(spend_txn[1], spend_txn[3]);
9438 assert_eq!(spend_txn[1], spend_txn[5]);
9439 assert_eq!(spend_txn[1], spend_txn[7]);
9440 check_spends!(spend_txn[0], local_txn[0].clone());
9441 check_spends!(spend_txn[1], node_txn[0].clone());
9445 fn test_static_output_closing_tx() {
9446 let nodes = create_network(2);
9448 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9450 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9451 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9453 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9454 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9455 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9456 assert_eq!(spend_txn.len(), 1);
9457 check_spends!(spend_txn[0], closing_tx.clone());
9459 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9460 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9461 assert_eq!(spend_txn.len(), 1);
9462 check_spends!(spend_txn[0], closing_tx);