1 //! The top-level channel management and payment tracking stuff lives here.
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
17 use secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
26 use ln::router::{Route,RouteHop};
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
39 use crypto::mac::{Mac,MacResult};
40 use crypto::hmac::Hmac;
41 use crypto::digest::Digest;
42 use crypto::symmetriccipher::SynchronousStreamCipher;
44 use std::{cmp, ptr, mem};
45 use std::collections::{HashMap, hash_map, HashSet};
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
65 use ln::router::Route;
66 use secp256k1::key::SecretKey;
68 /// Stores the info we will need to send when we want to forward an HTLC onwards
69 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
70 pub struct PendingForwardHTLCInfo {
71 pub(super) onion_packet: Option<msgs::OnionPacket>,
72 pub(super) incoming_shared_secret: [u8; 32],
73 pub(super) payment_hash: [u8; 32],
74 pub(super) short_channel_id: u64,
75 pub(super) amt_to_forward: u64,
76 pub(super) outgoing_cltv_value: u32,
79 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
80 pub enum HTLCFailureMsg {
81 Relay(msgs::UpdateFailHTLC),
82 Malformed(msgs::UpdateFailMalformedHTLC),
85 /// Stores whether we can't forward an HTLC or relevant forwarding info
86 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
87 pub enum PendingHTLCStatus {
88 Forward(PendingForwardHTLCInfo),
92 /// Tracks the inbound corresponding to an outbound HTLC
93 #[derive(Clone, PartialEq)]
94 pub struct HTLCPreviousHopData {
95 pub(super) short_channel_id: u64,
96 pub(super) htlc_id: u64,
97 pub(super) incoming_packet_shared_secret: [u8; 32],
100 /// Tracks the inbound corresponding to an outbound HTLC
101 #[derive(Clone, PartialEq)]
102 pub enum HTLCSource {
103 PreviousHopData(HTLCPreviousHopData),
106 session_priv: SecretKey,
107 /// Technically we can recalculate this from the route, but we cache it here to avoid
108 /// doing a double-pass on route when we get a failure back
109 first_hop_htlc_msat: u64,
114 pub fn dummy() -> Self {
115 HTLCSource::OutboundRoute {
116 route: Route { hops: Vec::new() },
117 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
118 first_hop_htlc_msat: 0,
123 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
124 pub(crate) enum HTLCFailReason {
126 err: msgs::OnionErrorPacket,
134 pub(super) use self::channel_held_info::*;
136 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>);
138 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
139 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
140 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
141 /// channel_state lock. We then return the set of things that need to be done outside the lock in
142 /// this struct and call handle_error!() on it.
143 struct MsgHandleErrInternal {
144 err: msgs::HandleError,
145 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
147 impl MsgHandleErrInternal {
149 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
153 action: Some(msgs::ErrorAction::SendErrorMessage {
154 msg: msgs::ErrorMessage {
156 data: err.to_string()
160 shutdown_finish: None,
164 fn from_no_close(err: msgs::HandleError) -> Self {
165 Self { err, shutdown_finish: None }
168 fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
172 action: Some(msgs::ErrorAction::SendErrorMessage {
173 msg: msgs::ErrorMessage {
175 data: err.to_string()
179 shutdown_finish: Some((shutdown_res, channel_update)),
183 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
186 ChannelError::Ignore(msg) => HandleError {
188 action: Some(msgs::ErrorAction::IgnoreError),
190 ChannelError::Close(msg) => HandleError {
192 action: Some(msgs::ErrorAction::SendErrorMessage {
193 msg: msgs::ErrorMessage {
195 data: msg.to_string()
200 shutdown_finish: None,
205 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
206 /// after a PaymentReceived event.
208 pub enum PaymentFailReason {
209 /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
211 /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
215 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
216 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
217 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
218 /// probably increase this significantly.
219 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
221 struct HTLCForwardInfo {
222 prev_short_channel_id: u64,
224 forward_info: PendingForwardHTLCInfo,
227 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
228 /// be sent in the order they appear in the return value, however sometimes the order needs to be
229 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
230 /// they were originally sent). In those cases, this enum is also returned.
231 #[derive(Clone, PartialEq)]
232 pub(super) enum RAACommitmentOrder {
233 /// Send the CommitmentUpdate messages first
235 /// Send the RevokeAndACK message first
239 struct ChannelHolder {
240 by_id: HashMap<[u8; 32], Channel>,
241 short_to_id: HashMap<u64, [u8; 32]>,
242 next_forward: Instant,
243 /// short channel id -> forward infos. Key of 0 means payments received
244 /// Note that while this is held in the same mutex as the channels themselves, no consistency
245 /// guarantees are made about there existing a channel with the short id here, nor the short
246 /// ids in the PendingForwardHTLCInfo!
247 forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
248 /// Note that while this is held in the same mutex as the channels themselves, no consistency
249 /// guarantees are made about the channels given here actually existing anymore by the time you
251 claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
252 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
253 /// for broadcast messages, where ordering isn't as strict).
254 pending_msg_events: Vec<events::MessageSendEvent>,
256 struct MutChannelHolder<'a> {
257 by_id: &'a mut HashMap<[u8; 32], Channel>,
258 short_to_id: &'a mut HashMap<u64, [u8; 32]>,
259 next_forward: &'a mut Instant,
260 forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
261 claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
262 pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
265 fn borrow_parts(&mut self) -> MutChannelHolder {
267 by_id: &mut self.by_id,
268 short_to_id: &mut self.short_to_id,
269 next_forward: &mut self.next_forward,
270 forward_htlcs: &mut self.forward_htlcs,
271 claimable_htlcs: &mut self.claimable_htlcs,
272 pending_msg_events: &mut self.pending_msg_events,
277 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
278 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
280 /// Manager which keeps track of a number of channels and sends messages to the appropriate
281 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
283 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
284 /// to individual Channels.
286 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
287 /// all peers during write/read (though does not modify this instance, only the instance being
288 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
289 /// called funding_transaction_generated for outbound channels).
291 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
292 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
293 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
294 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
295 /// the serialization process). If the deserialized version is out-of-date compared to the
296 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
297 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
299 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
300 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
301 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
302 /// block_connected() to step towards your best block) upon deserialization before using the
304 pub struct ChannelManager {
305 default_configuration: UserConfig,
306 genesis_hash: Sha256dHash,
307 fee_estimator: Arc<FeeEstimator>,
308 monitor: Arc<ManyChannelMonitor>,
309 chain_monitor: Arc<ChainWatchInterface>,
310 tx_broadcaster: Arc<BroadcasterInterface>,
312 latest_block_height: AtomicUsize,
313 last_block_hash: Mutex<Sha256dHash>,
314 secp_ctx: Secp256k1<secp256k1::All>,
316 channel_state: Mutex<ChannelHolder>,
317 our_network_key: SecretKey,
319 pending_events: Mutex<Vec<events::Event>>,
320 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
321 /// Essentially just when we're serializing ourselves out.
322 /// Taken first everywhere where we are making changes before any other locks.
323 total_consistency_lock: RwLock<()>,
325 keys_manager: Arc<KeysInterface>,
330 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
331 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
332 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
333 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
334 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
335 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
336 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
338 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
339 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
340 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
341 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
344 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
346 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
347 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
350 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
352 macro_rules! secp_call {
353 ( $res: expr, $err: expr ) => {
356 Err(_) => return Err($err),
363 shared_secret: SharedSecret,
365 blinding_factor: [u8; 32],
366 ephemeral_pubkey: PublicKey,
371 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
372 pub struct ChannelDetails {
373 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
374 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
375 /// Note that this means this value is *not* persistent - it can change once during the
376 /// lifetime of the channel.
377 pub channel_id: [u8; 32],
378 /// The position of the funding transaction in the chain. None if the funding transaction has
379 /// not yet been confirmed and the channel fully opened.
380 pub short_channel_id: Option<u64>,
381 /// The node_id of our counterparty
382 pub remote_network_id: PublicKey,
383 /// The value, in satoshis, of this channel as appears in the funding output
384 pub channel_value_satoshis: u64,
385 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
389 macro_rules! handle_error {
390 ($self: ident, $internal: expr, $their_node_id: expr) => {
393 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
394 if let Some((shutdown_res, update_option)) = shutdown_finish {
395 $self.finish_force_close_channel(shutdown_res);
396 if let Some(update) = update_option {
397 let mut channel_state = $self.channel_state.lock().unwrap();
398 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
409 macro_rules! break_chan_entry {
410 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
413 Err(ChannelError::Ignore(msg)) => {
414 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
416 Err(ChannelError::Close(msg)) => {
417 let (channel_id, mut chan) = $entry.remove_entry();
418 if let Some(short_id) = chan.get_short_channel_id() {
419 $channel_state.short_to_id.remove(&short_id);
421 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
427 macro_rules! try_chan_entry {
428 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
431 Err(ChannelError::Ignore(msg)) => {
432 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
434 Err(ChannelError::Close(msg)) => {
435 let (channel_id, mut chan) = $entry.remove_entry();
436 if let Some(short_id) = chan.get_short_channel_id() {
437 $channel_state.short_to_id.remove(&short_id);
439 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
445 macro_rules! return_monitor_err {
446 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
447 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
449 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
450 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
451 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
453 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
454 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
456 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
458 ChannelMonitorUpdateErr::PermanentFailure => {
459 let (channel_id, mut chan) = $entry.remove_entry();
460 if let Some(short_id) = chan.get_short_channel_id() {
461 $channel_state.short_to_id.remove(&short_id);
463 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
464 // chain in a confused state! We need to move them into the ChannelMonitor which
465 // will be responsible for failing backwards once things confirm on-chain.
466 // It's ok that we drop $failed_forwards here - at this point we'd rather they
467 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
468 // us bother trying to claim it just to forward on to another peer. If we're
469 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
470 // given up the preimage yet, so might as well just wait until the payment is
471 // retried, avoiding the on-chain fees.
472 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
474 ChannelMonitorUpdateErr::TemporaryFailure => {
475 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
476 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
482 // Does not break in case of TemporaryFailure!
483 macro_rules! maybe_break_monitor_err {
484 ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
486 ChannelMonitorUpdateErr::PermanentFailure => {
487 let (channel_id, mut chan) = $entry.remove_entry();
488 if let Some(short_id) = chan.get_short_channel_id() {
489 $channel_state.short_to_id.remove(&short_id);
491 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
493 ChannelMonitorUpdateErr::TemporaryFailure => {
494 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
500 impl ChannelManager {
501 /// Constructs a new ChannelManager to hold several channels and route between them.
503 /// This is the main "logic hub" for all channel-related actions, and implements
504 /// ChannelMessageHandler.
506 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
508 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
509 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> {
510 let secp_ctx = Secp256k1::new();
512 let res = Arc::new(ChannelManager {
513 default_configuration: config.clone(),
514 genesis_hash: genesis_block(network).header.bitcoin_hash(),
515 fee_estimator: feeest.clone(),
516 monitor: monitor.clone(),
520 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
521 last_block_hash: Mutex::new(Default::default()),
524 channel_state: Mutex::new(ChannelHolder{
525 by_id: HashMap::new(),
526 short_to_id: HashMap::new(),
527 next_forward: Instant::now(),
528 forward_htlcs: HashMap::new(),
529 claimable_htlcs: HashMap::new(),
530 pending_msg_events: Vec::new(),
532 our_network_key: keys_manager.get_node_secret(),
534 pending_events: Mutex::new(Vec::new()),
535 total_consistency_lock: RwLock::new(()),
541 let weak_res = Arc::downgrade(&res);
542 res.chain_monitor.register_listener(weak_res);
546 /// Creates a new outbound channel to the given remote node and with the given value.
548 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
549 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
550 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
551 /// may wish to avoid using 0 for user_id here.
553 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
554 /// PeerManager::process_events afterwards.
556 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
557 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
558 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
559 if channel_value_satoshis < 1000 {
560 return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
563 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)?;
564 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
566 let _ = self.total_consistency_lock.read().unwrap();
567 let mut channel_state = self.channel_state.lock().unwrap();
568 match channel_state.by_id.entry(channel.channel_id()) {
569 hash_map::Entry::Occupied(_) => {
570 if cfg!(feature = "fuzztarget") {
571 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
573 panic!("RNG is bad???");
576 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
578 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
579 node_id: their_network_key,
585 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
586 /// more information.
587 pub fn list_channels(&self) -> Vec<ChannelDetails> {
588 let channel_state = self.channel_state.lock().unwrap();
589 let mut res = Vec::with_capacity(channel_state.by_id.len());
590 for (channel_id, channel) in channel_state.by_id.iter() {
591 res.push(ChannelDetails {
592 channel_id: (*channel_id).clone(),
593 short_channel_id: channel.get_short_channel_id(),
594 remote_network_id: channel.get_their_node_id(),
595 channel_value_satoshis: channel.get_value_satoshis(),
596 user_id: channel.get_user_id(),
602 /// Gets the list of usable channels, in random order. Useful as an argument to
603 /// Router::get_route to ensure non-announced channels are used.
604 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
605 let channel_state = self.channel_state.lock().unwrap();
606 let mut res = Vec::with_capacity(channel_state.by_id.len());
607 for (channel_id, channel) in channel_state.by_id.iter() {
608 // Note we use is_live here instead of usable which leads to somewhat confused
609 // internal/external nomenclature, but that's ok cause that's probably what the user
610 // really wanted anyway.
611 if channel.is_live() {
612 res.push(ChannelDetails {
613 channel_id: (*channel_id).clone(),
614 short_channel_id: channel.get_short_channel_id(),
615 remote_network_id: channel.get_their_node_id(),
616 channel_value_satoshis: channel.get_value_satoshis(),
617 user_id: channel.get_user_id(),
624 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
625 /// will be accepted on the given channel, and after additional timeout/the closing of all
626 /// pending HTLCs, the channel will be closed on chain.
628 /// May generate a SendShutdown message event on success, which should be relayed.
629 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
630 let _ = self.total_consistency_lock.read().unwrap();
632 let (mut failed_htlcs, chan_option) = {
633 let mut channel_state_lock = self.channel_state.lock().unwrap();
634 let channel_state = channel_state_lock.borrow_parts();
635 match channel_state.by_id.entry(channel_id.clone()) {
636 hash_map::Entry::Occupied(mut chan_entry) => {
637 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
638 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
639 node_id: chan_entry.get().get_their_node_id(),
642 if chan_entry.get().is_shutdown() {
643 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
644 channel_state.short_to_id.remove(&short_id);
646 (failed_htlcs, Some(chan_entry.remove_entry().1))
647 } else { (failed_htlcs, None) }
649 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
652 for htlc_source in failed_htlcs.drain(..) {
653 // unknown_next_peer...I dunno who that is anymore....
654 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
656 let chan_update = if let Some(chan) = chan_option {
657 if let Ok(update) = self.get_channel_update(&chan) {
662 if let Some(update) = chan_update {
663 let mut channel_state = self.channel_state.lock().unwrap();
664 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
673 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
674 let (local_txn, mut failed_htlcs) = shutdown_res;
675 for htlc_source in failed_htlcs.drain(..) {
676 // unknown_next_peer...I dunno who that is anymore....
677 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
679 for tx in local_txn {
680 self.tx_broadcaster.broadcast_transaction(&tx);
684 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
685 /// the chain and rejecting new HTLCs on the given channel.
686 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
687 let _ = self.total_consistency_lock.read().unwrap();
690 let mut channel_state_lock = self.channel_state.lock().unwrap();
691 let channel_state = channel_state_lock.borrow_parts();
692 if let Some(chan) = channel_state.by_id.remove(channel_id) {
693 if let Some(short_id) = chan.get_short_channel_id() {
694 channel_state.short_to_id.remove(&short_id);
701 self.finish_force_close_channel(chan.force_shutdown());
702 if let Ok(update) = self.get_channel_update(&chan) {
703 let mut channel_state = self.channel_state.lock().unwrap();
704 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
710 /// Force close all channels, immediately broadcasting the latest local commitment transaction
711 /// for each to the chain and rejecting new HTLCs on each.
712 pub fn force_close_all_channels(&self) {
713 for chan in self.list_channels() {
714 self.force_close_channel(&chan.channel_id);
719 fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
720 assert_eq!(shared_secret.len(), 32);
722 let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
723 hmac.input(&shared_secret[..]);
724 let mut res = [0; 32];
725 hmac.raw_result(&mut res);
729 let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
730 hmac.input(&shared_secret[..]);
731 let mut res = [0; 32];
732 hmac.raw_result(&mut res);
738 fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
739 assert_eq!(shared_secret.len(), 32);
740 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
741 hmac.input(&shared_secret[..]);
742 let mut res = [0; 32];
743 hmac.raw_result(&mut res);
748 fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
749 assert_eq!(shared_secret.len(), 32);
750 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
751 hmac.input(&shared_secret[..]);
752 let mut res = [0; 32];
753 hmac.raw_result(&mut res);
757 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
759 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> {
760 let mut blinded_priv = session_priv.clone();
761 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
763 for hop in route.hops.iter() {
764 let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
766 let mut sha = Sha256::new();
767 sha.input(&blinded_pub.serialize()[..]);
768 sha.input(&shared_secret[..]);
769 let mut blinding_factor = [0u8; 32];
770 sha.result(&mut blinding_factor);
772 let ephemeral_pubkey = blinded_pub;
774 blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
775 blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
777 callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
783 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
784 fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
785 let mut res = Vec::with_capacity(route.hops.len());
787 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
788 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
794 blinding_factor: _blinding_factor,
804 /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
805 fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
806 let mut cur_value_msat = 0u64;
807 let mut cur_cltv = starting_htlc_offset;
808 let mut last_short_channel_id = 0;
809 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
810 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
811 unsafe { res.set_len(route.hops.len()); }
813 for (idx, hop) in route.hops.iter().enumerate().rev() {
814 // First hop gets special values so that it can check, on receipt, that everything is
815 // exactly as it should be (and the next hop isn't trying to probe to find out if we're
816 // the intended recipient).
817 let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
818 let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
819 res[idx] = msgs::OnionHopData {
821 data: msgs::OnionRealm0HopData {
822 short_channel_id: last_short_channel_id,
823 amt_to_forward: value_msat,
824 outgoing_cltv_value: cltv,
828 cur_value_msat += hop.fee_msat;
829 if cur_value_msat >= 21000000 * 100000000 * 1000 {
830 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
832 cur_cltv += hop.cltv_expiry_delta as u32;
833 if cur_cltv >= 500000000 {
834 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
836 last_short_channel_id = hop.short_channel_id;
838 Ok((res, cur_value_msat, cur_cltv))
842 fn shift_arr_right(arr: &mut [u8; 20*65]) {
844 ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
852 fn xor_bufs(dst: &mut[u8], src: &[u8]) {
853 assert_eq!(dst.len(), src.len());
855 for i in 0..dst.len() {
860 const ZERO:[u8; 21*65] = [0; 21*65];
861 fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
862 let mut buf = Vec::with_capacity(21*65);
863 buf.resize(21*65, 0);
866 let iters = payloads.len() - 1;
867 let end_len = iters * 65;
868 let mut res = Vec::with_capacity(end_len);
869 res.resize(end_len, 0);
871 for (i, keys) in onion_keys.iter().enumerate() {
872 if i == payloads.len() - 1 { continue; }
873 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
874 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
875 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
880 let mut packet_data = [0; 20*65];
881 let mut hmac_res = [0; 32];
883 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
884 ChannelManager::shift_arr_right(&mut packet_data);
885 payload.hmac = hmac_res;
886 packet_data[0..65].copy_from_slice(&payload.encode()[..]);
888 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
889 chacha.process(&packet_data, &mut buf[0..20*65]);
890 packet_data[..].copy_from_slice(&buf[0..20*65]);
893 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
896 let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
897 hmac.input(&packet_data);
898 hmac.input(&associated_data[..]);
899 hmac.raw_result(&mut hmac_res);
904 public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
905 hop_data: packet_data,
910 /// Encrypts a failure packet. raw_packet can either be a
911 /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
912 fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
913 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
915 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
916 packet_crypted.resize(raw_packet.len(), 0);
917 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
918 chacha.process(&raw_packet, &mut packet_crypted[..]);
919 msgs::OnionErrorPacket {
920 data: packet_crypted,
924 fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
925 assert_eq!(shared_secret.len(), 32);
926 assert!(failure_data.len() <= 256 - 2);
928 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
931 let mut res = Vec::with_capacity(2 + failure_data.len());
932 res.push(((failure_type >> 8) & 0xff) as u8);
933 res.push(((failure_type >> 0) & 0xff) as u8);
934 res.extend_from_slice(&failure_data[..]);
938 let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
939 res.resize(256 - 2 - failure_data.len(), 0);
942 let mut packet = msgs::DecodedOnionErrorPacket {
944 failuremsg: failuremsg,
948 let mut hmac = Hmac::new(Sha256::new(), &um);
949 hmac.input(&packet.encode()[32..]);
950 hmac.raw_result(&mut packet.hmac);
956 fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
957 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
958 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
961 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
962 macro_rules! get_onion_hash {
965 let mut sha = Sha256::new();
966 sha.input(&msg.onion_routing_packet.hop_data);
967 let mut onion_hash = [0; 32];
968 sha.result(&mut onion_hash);
974 if let Err(_) = msg.onion_routing_packet.public_key {
975 log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
976 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
977 channel_id: msg.channel_id,
978 htlc_id: msg.htlc_id,
979 sha256_of_onion: get_onion_hash!(),
980 failure_code: 0x8000 | 0x4000 | 6,
981 })), self.channel_state.lock().unwrap());
984 let shared_secret = {
985 let mut arr = [0; 32];
986 arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
989 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
991 let mut channel_state = None;
992 macro_rules! return_err {
993 ($msg: expr, $err_code: expr, $data: expr) => {
995 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
996 if channel_state.is_none() {
997 channel_state = Some(self.channel_state.lock().unwrap());
999 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1000 channel_id: msg.channel_id,
1001 htlc_id: msg.htlc_id,
1002 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1003 })), channel_state.unwrap());
1008 if msg.onion_routing_packet.version != 0 {
1009 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1010 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1011 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1012 //receiving node would have to brute force to figure out which version was put in the
1013 //packet by the node that send us the message, in the case of hashing the hop_data, the
1014 //node knows the HMAC matched, so they already know what is there...
1015 return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1018 let mut hmac = Hmac::new(Sha256::new(), &mu);
1019 hmac.input(&msg.onion_routing_packet.hop_data);
1020 hmac.input(&msg.payment_hash);
1021 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1022 return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1025 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1026 let next_hop_data = {
1027 let mut decoded = [0; 65];
1028 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1029 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1031 let error_code = match err {
1032 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1033 _ => 0x2000 | 2, // Should never happen
1035 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1041 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1043 // final_expiry_too_soon
1044 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1045 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1047 // final_incorrect_htlc_amount
1048 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1049 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1051 // final_incorrect_cltv_expiry
1052 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1053 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1056 // Note that we could obviously respond immediately with an update_fulfill_htlc
1057 // message, however that would leak that we are the recipient of this payment, so
1058 // instead we stay symmetric with the forwarding case, only responding (after a
1059 // delay) once they've send us a commitment_signed!
1061 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1063 payment_hash: msg.payment_hash.clone(),
1064 short_channel_id: 0,
1065 incoming_shared_secret: shared_secret,
1066 amt_to_forward: next_hop_data.data.amt_to_forward,
1067 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1070 let mut new_packet_data = [0; 20*65];
1071 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1072 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1074 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1076 let blinding_factor = {
1077 let mut sha = Sha256::new();
1078 sha.input(&new_pubkey.serialize()[..]);
1079 sha.input(&shared_secret);
1080 let mut res = [0u8; 32];
1081 sha.result(&mut res);
1082 match SecretKey::from_slice(&self.secp_ctx, &res) {
1084 return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1090 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1091 return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1094 let outgoing_packet = msgs::OnionPacket {
1096 public_key: Ok(new_pubkey),
1097 hop_data: new_packet_data,
1098 hmac: next_hop_data.hmac.clone(),
1101 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1102 onion_packet: Some(outgoing_packet),
1103 payment_hash: msg.payment_hash.clone(),
1104 short_channel_id: next_hop_data.data.short_channel_id,
1105 incoming_shared_secret: shared_secret,
1106 amt_to_forward: next_hop_data.data.amt_to_forward,
1107 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1111 channel_state = Some(self.channel_state.lock().unwrap());
1112 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1113 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1114 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1115 let forwarding_id = match id_option {
1116 None => { // unknown_next_peer
1117 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1119 Some(id) => id.clone(),
1121 if let Some((err, code, chan_update)) = loop {
1122 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1124 // Note that we could technically not return an error yet here and just hope
1125 // that the connection is reestablished or monitor updated by the time we get
1126 // around to doing the actual forward, but better to fail early if we can and
1127 // hopefully an attacker trying to path-trace payments cannot make this occur
1128 // on a small/per-node/per-channel scale.
1129 if !chan.is_live() { // channel_disabled
1130 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1132 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1133 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1135 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) });
1136 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1137 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())));
1139 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1140 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())));
1142 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1143 // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1144 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1145 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1147 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1148 break Some(("CLTV expiry is too far in the future", 21, None));
1153 let mut res = Vec::with_capacity(8 + 128);
1154 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1155 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1157 else if code == 0x1000 | 13 {
1158 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1160 if let Some(chan_update) = chan_update {
1161 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1163 return_err!(err, code, &res[..]);
1168 (pending_forward_info, channel_state.unwrap())
1171 /// only fails if the channel does not yet have an assigned short_id
1172 /// May be called with channel_state already locked!
1173 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1174 let short_channel_id = match chan.get_short_channel_id() {
1175 None => return Err(HandleError{err: "Channel not yet established", action: None}),
1179 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1181 let unsigned = msgs::UnsignedChannelUpdate {
1182 chain_hash: self.genesis_hash,
1183 short_channel_id: short_channel_id,
1184 timestamp: chan.get_channel_update_count(),
1185 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1186 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1187 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1188 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1189 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1190 excess_data: Vec::new(),
1193 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1194 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1196 Ok(msgs::ChannelUpdate {
1202 /// Sends a payment along a given route.
1204 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1205 /// fields for more info.
1207 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1208 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1209 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1210 /// specified in the last hop in the route! Thus, you should probably do your own
1211 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1212 /// payment") and prevent double-sends yourself.
1214 /// May generate a SendHTLCs message event on success, which should be relayed.
1216 /// Raises APIError::RoutError when invalid route or forward parameter
1217 /// (cltv_delta, fee, node public key) is specified.
1218 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1219 /// (including due to previous monitor update failure or new permanent monitor update failure).
1220 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1221 /// relevant updates.
1223 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1224 /// and you may wish to retry via a different route immediately.
1225 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1226 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1227 /// the payment via a different route unless you intend to pay twice!
1228 pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1229 if route.hops.len() < 1 || route.hops.len() > 20 {
1230 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1232 let our_node_id = self.get_our_node_id();
1233 for (idx, hop) in route.hops.iter().enumerate() {
1234 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1235 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1239 let session_priv = self.keys_manager.get_session_key();
1241 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1243 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1244 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1245 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1246 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1248 let _ = self.total_consistency_lock.read().unwrap();
1250 let err: Result<(), _> = loop {
1251 let mut channel_lock = self.channel_state.lock().unwrap();
1253 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1254 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1255 Some(id) => id.clone(),
1258 let channel_state = channel_lock.borrow_parts();
1259 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1261 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1262 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1264 if !chan.get().is_live() {
1265 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1267 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1268 route: route.clone(),
1269 session_priv: session_priv.clone(),
1270 first_hop_htlc_msat: htlc_msat,
1271 }, onion_packet), channel_state, chan)
1273 Some((update_add, commitment_signed, chan_monitor)) => {
1274 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1275 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1276 // Note that MonitorUpdateFailed here indicates (per function docs)
1277 // that we will resent the commitment update once we unfree monitor
1278 // updating, so we have to take special care that we don't return
1279 // something else in case we will resend later!
1280 return Err(APIError::MonitorUpdateFailed);
1283 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1284 node_id: route.hops.first().unwrap().pubkey,
1285 updates: msgs::CommitmentUpdate {
1286 update_add_htlcs: vec![update_add],
1287 update_fulfill_htlcs: Vec::new(),
1288 update_fail_htlcs: Vec::new(),
1289 update_fail_malformed_htlcs: Vec::new(),
1297 } else { unreachable!(); }
1301 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1302 Ok(_) => unreachable!(),
1304 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1306 log_error!(self, "Got bad keys: {}!", e.err);
1307 let mut channel_state = self.channel_state.lock().unwrap();
1308 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1309 node_id: route.hops.first().unwrap().pubkey,
1313 Err(APIError::ChannelUnavailable { err: e.err })
1318 /// Call this upon creation of a funding transaction for the given channel.
1320 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1321 /// or your counterparty can steal your funds!
1323 /// Panics if a funding transaction has already been provided for this channel.
1325 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1326 /// be trivially prevented by using unique funding transaction keys per-channel).
1327 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1328 let _ = self.total_consistency_lock.read().unwrap();
1330 let (chan, msg, chan_monitor) = {
1332 let mut channel_state = self.channel_state.lock().unwrap();
1333 match channel_state.by_id.remove(temporary_channel_id) {
1335 (chan.get_outbound_funding_created(funding_txo)
1336 .map_err(|e| if let ChannelError::Close(msg) = e {
1337 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1338 } else { unreachable!(); })
1344 match handle_error!(self, res, chan.get_their_node_id()) {
1345 Ok(funding_msg) => {
1346 (chan, funding_msg.0, funding_msg.1)
1349 log_error!(self, "Got bad signatures: {}!", e.err);
1350 let mut channel_state = self.channel_state.lock().unwrap();
1351 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1352 node_id: chan.get_their_node_id(),
1359 // Because we have exclusive ownership of the channel here we can release the channel_state
1360 // lock before add_update_monitor
1361 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1365 let mut channel_state = self.channel_state.lock().unwrap();
1366 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1367 node_id: chan.get_their_node_id(),
1370 match channel_state.by_id.entry(chan.channel_id()) {
1371 hash_map::Entry::Occupied(_) => {
1372 panic!("Generated duplicate funding txid?");
1374 hash_map::Entry::Vacant(e) => {
1380 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1381 if !chan.should_announce() { return None }
1383 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1385 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1387 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1388 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1390 Some(msgs::AnnouncementSignatures {
1391 channel_id: chan.channel_id(),
1392 short_channel_id: chan.get_short_channel_id().unwrap(),
1393 node_signature: our_node_sig,
1394 bitcoin_signature: our_bitcoin_sig,
1398 /// Processes HTLCs which are pending waiting on random forward delay.
1400 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1401 /// Will likely generate further events.
1402 pub fn process_pending_htlc_forwards(&self) {
1403 let _ = self.total_consistency_lock.read().unwrap();
1405 let mut new_events = Vec::new();
1406 let mut failed_forwards = Vec::new();
1408 let mut channel_state_lock = self.channel_state.lock().unwrap();
1409 let channel_state = channel_state_lock.borrow_parts();
1411 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1415 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1416 if short_chan_id != 0 {
1417 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1418 Some(chan_id) => chan_id.clone(),
1420 failed_forwards.reserve(pending_forwards.len());
1421 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1422 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1423 short_channel_id: prev_short_channel_id,
1424 htlc_id: prev_htlc_id,
1425 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1427 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1432 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1434 let mut add_htlc_msgs = Vec::new();
1435 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1436 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1437 short_channel_id: prev_short_channel_id,
1438 htlc_id: prev_htlc_id,
1439 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1441 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()) {
1443 let chan_update = self.get_channel_update(forward_chan).unwrap();
1444 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1449 Some(msg) => { add_htlc_msgs.push(msg); },
1451 // Nothing to do here...we're waiting on a remote
1452 // revoke_and_ack before we can add anymore HTLCs. The Channel
1453 // will automatically handle building the update_add_htlc and
1454 // commitment_signed messages when we can.
1455 // TODO: Do some kind of timer to set the channel as !is_live()
1456 // as we don't really want others relying on us relaying through
1457 // this channel currently :/.
1464 if !add_htlc_msgs.is_empty() {
1465 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1468 if let ChannelError::Ignore(_) = e {
1469 panic!("Stated return value requirements in send_commitment() were not met");
1471 //TODO: Handle...this is bad!
1475 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1478 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1479 node_id: forward_chan.get_their_node_id(),
1480 updates: msgs::CommitmentUpdate {
1481 update_add_htlcs: add_htlc_msgs,
1482 update_fulfill_htlcs: Vec::new(),
1483 update_fail_htlcs: Vec::new(),
1484 update_fail_malformed_htlcs: Vec::new(),
1486 commitment_signed: commitment_msg,
1491 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1492 let prev_hop_data = HTLCPreviousHopData {
1493 short_channel_id: prev_short_channel_id,
1494 htlc_id: prev_htlc_id,
1495 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1497 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1498 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1499 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1501 new_events.push(events::Event::PaymentReceived {
1502 payment_hash: forward_info.payment_hash,
1503 amt: forward_info.amt_to_forward,
1510 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1512 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1513 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() }),
1517 if new_events.is_empty() { return }
1518 let mut events = self.pending_events.lock().unwrap();
1519 events.append(&mut new_events);
1522 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1523 pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32], reason: PaymentFailReason) -> bool {
1524 let _ = self.total_consistency_lock.read().unwrap();
1526 let mut channel_state = Some(self.channel_state.lock().unwrap());
1527 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1528 if let Some(mut sources) = removed_source {
1529 for htlc_with_hash in sources.drain(..) {
1530 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1531 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() });
1537 /// Fails an HTLC backwards to the sender of it to us.
1538 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1539 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1540 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1541 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1542 /// still-available channels.
1543 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1545 HTLCSource::OutboundRoute { .. } => {
1546 mem::drop(channel_state_lock);
1547 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1548 let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1549 if let Some(update) = channel_update {
1550 self.channel_state.lock().unwrap().pending_msg_events.push(
1551 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1556 self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1557 payment_hash: payment_hash.clone(),
1558 rejected_by_dest: !payment_retryable,
1561 //TODO: Pass this back (see GH #243)
1562 self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1563 payment_hash: payment_hash.clone(),
1564 rejected_by_dest: false, // We failed it ourselves, can't blame them
1568 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1569 let err_packet = match onion_error {
1570 HTLCFailReason::Reason { failure_code, data } => {
1571 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1572 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1574 HTLCFailReason::ErrorPacket { err } => {
1575 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1579 let channel_state = channel_state_lock.borrow_parts();
1581 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1582 Some(chan_id) => chan_id.clone(),
1586 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1587 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1588 Ok(Some((msg, commitment_msg, chan_monitor))) => {
1589 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1592 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1593 node_id: chan.get_their_node_id(),
1594 updates: msgs::CommitmentUpdate {
1595 update_add_htlcs: Vec::new(),
1596 update_fulfill_htlcs: Vec::new(),
1597 update_fail_htlcs: vec![msg],
1598 update_fail_malformed_htlcs: Vec::new(),
1600 commitment_signed: commitment_msg,
1606 //TODO: Do something with e?
1614 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1615 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1616 /// should probably kick the net layer to go send messages if this returns true!
1618 /// May panic if called except in response to a PaymentReceived event.
1619 pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1620 let mut sha = Sha256::new();
1621 sha.input(&payment_preimage);
1622 let mut payment_hash = [0; 32];
1623 sha.result(&mut payment_hash);
1625 let _ = self.total_consistency_lock.read().unwrap();
1627 let mut channel_state = Some(self.channel_state.lock().unwrap());
1628 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1629 if let Some(mut sources) = removed_source {
1630 for htlc_with_hash in sources.drain(..) {
1631 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1632 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1637 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1639 HTLCSource::OutboundRoute { .. } => {
1640 mem::drop(channel_state_lock);
1641 let mut pending_events = self.pending_events.lock().unwrap();
1642 pending_events.push(events::Event::PaymentSent {
1646 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1647 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1648 let channel_state = channel_state_lock.borrow_parts();
1650 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1651 Some(chan_id) => chan_id.clone(),
1653 // TODO: There is probably a channel manager somewhere that needs to
1654 // learn the preimage as the channel already hit the chain and that's
1660 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1661 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1662 Ok((msgs, monitor_option)) => {
1663 if let Some(chan_monitor) = monitor_option {
1664 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1665 unimplemented!();// but def dont push the event...
1668 if let Some((msg, commitment_signed)) = msgs {
1669 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1670 node_id: chan.get_their_node_id(),
1671 updates: msgs::CommitmentUpdate {
1672 update_add_htlcs: Vec::new(),
1673 update_fulfill_htlcs: vec![msg],
1674 update_fail_htlcs: Vec::new(),
1675 update_fail_malformed_htlcs: Vec::new(),
1683 // TODO: There is probably a channel manager somewhere that needs to
1684 // learn the preimage as the channel may be about to hit the chain.
1685 //TODO: Do something with e?
1693 /// Gets the node_id held by this ChannelManager
1694 pub fn get_our_node_id(&self) -> PublicKey {
1695 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1698 /// Used to restore channels to normal operation after a
1699 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1701 pub fn test_restore_channel_monitor(&self) {
1702 let mut close_results = Vec::new();
1703 let mut htlc_forwards = Vec::new();
1704 let mut htlc_failures = Vec::new();
1705 let _ = self.total_consistency_lock.read().unwrap();
1708 let mut channel_lock = self.channel_state.lock().unwrap();
1709 let channel_state = channel_lock.borrow_parts();
1710 let short_to_id = channel_state.short_to_id;
1711 let pending_msg_events = channel_state.pending_msg_events;
1712 channel_state.by_id.retain(|_, channel| {
1713 if channel.is_awaiting_monitor_update() {
1714 let chan_monitor = channel.channel_monitor();
1715 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1717 ChannelMonitorUpdateErr::PermanentFailure => {
1718 // TODO: There may be some pending HTLCs that we intended to fail
1719 // backwards when a monitor update failed. We should make sure
1720 // knowledge of those gets moved into the appropriate in-memory
1721 // ChannelMonitor and they get failed backwards once we get
1722 // on-chain confirmations.
1723 // Note I think #198 addresses this, so once its merged a test
1724 // should be written.
1725 if let Some(short_id) = channel.get_short_channel_id() {
1726 short_to_id.remove(&short_id);
1728 close_results.push(channel.force_shutdown());
1729 if let Ok(update) = self.get_channel_update(&channel) {
1730 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1736 ChannelMonitorUpdateErr::TemporaryFailure => true,
1739 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1740 if !pending_forwards.is_empty() {
1741 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1743 htlc_failures.append(&mut pending_failures);
1745 macro_rules! handle_cs { () => {
1746 if let Some(update) = commitment_update {
1747 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1748 node_id: channel.get_their_node_id(),
1753 macro_rules! handle_raa { () => {
1754 if let Some(revoke_and_ack) = raa {
1755 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1756 node_id: channel.get_their_node_id(),
1757 msg: revoke_and_ack,
1762 RAACommitmentOrder::CommitmentFirst => {
1766 RAACommitmentOrder::RevokeAndACKFirst => {
1777 for failure in htlc_failures.drain(..) {
1778 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1780 self.forward_htlcs(&mut htlc_forwards[..]);
1782 for res in close_results.drain(..) {
1783 self.finish_force_close_channel(res);
1787 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1788 if msg.chain_hash != self.genesis_hash {
1789 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1792 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)
1793 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1794 let mut channel_state_lock = self.channel_state.lock().unwrap();
1795 let channel_state = channel_state_lock.borrow_parts();
1796 match channel_state.by_id.entry(channel.channel_id()) {
1797 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1798 hash_map::Entry::Vacant(entry) => {
1799 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1800 node_id: their_node_id.clone(),
1801 msg: channel.get_accept_channel(),
1803 entry.insert(channel);
1809 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1810 let (value, output_script, user_id) = {
1811 let mut channel_lock = self.channel_state.lock().unwrap();
1812 let channel_state = channel_lock.borrow_parts();
1813 match channel_state.by_id.entry(msg.temporary_channel_id) {
1814 hash_map::Entry::Occupied(mut chan) => {
1815 if chan.get().get_their_node_id() != *their_node_id {
1816 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1817 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1819 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1820 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1822 //TODO: same as above
1823 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1826 let mut pending_events = self.pending_events.lock().unwrap();
1827 pending_events.push(events::Event::FundingGenerationReady {
1828 temporary_channel_id: msg.temporary_channel_id,
1829 channel_value_satoshis: value,
1830 output_script: output_script,
1831 user_channel_id: user_id,
1836 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1837 let ((funding_msg, monitor_update), chan) = {
1838 let mut channel_lock = self.channel_state.lock().unwrap();
1839 let channel_state = channel_lock.borrow_parts();
1840 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1841 hash_map::Entry::Occupied(mut chan) => {
1842 if chan.get().get_their_node_id() != *their_node_id {
1843 //TODO: here and below MsgHandleErrInternal, #153 case
1844 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1846 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1848 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1851 // Because we have exclusive ownership of the channel here we can release the channel_state
1852 // lock before add_update_monitor
1853 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1856 let mut channel_state_lock = self.channel_state.lock().unwrap();
1857 let channel_state = channel_state_lock.borrow_parts();
1858 match channel_state.by_id.entry(funding_msg.channel_id) {
1859 hash_map::Entry::Occupied(_) => {
1860 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1862 hash_map::Entry::Vacant(e) => {
1863 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1864 node_id: their_node_id.clone(),
1873 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1874 let (funding_txo, user_id) = {
1875 let mut channel_lock = self.channel_state.lock().unwrap();
1876 let channel_state = channel_lock.borrow_parts();
1877 match channel_state.by_id.entry(msg.channel_id) {
1878 hash_map::Entry::Occupied(mut chan) => {
1879 if chan.get().get_their_node_id() != *their_node_id {
1880 //TODO: here and below MsgHandleErrInternal, #153 case
1881 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1883 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1884 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1887 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1889 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1892 let mut pending_events = self.pending_events.lock().unwrap();
1893 pending_events.push(events::Event::FundingBroadcastSafe {
1894 funding_txo: funding_txo,
1895 user_channel_id: user_id,
1900 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
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(msg.channel_id) {
1904 hash_map::Entry::Occupied(mut chan) => {
1905 if chan.get().get_their_node_id() != *their_node_id {
1906 //TODO: here and below MsgHandleErrInternal, #153 case
1907 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1909 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1910 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1911 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1912 node_id: their_node_id.clone(),
1913 msg: announcement_sigs,
1918 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1922 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1923 let (mut dropped_htlcs, chan_option) = {
1924 let mut channel_state_lock = self.channel_state.lock().unwrap();
1925 let channel_state = channel_state_lock.borrow_parts();
1927 match channel_state.by_id.entry(msg.channel_id.clone()) {
1928 hash_map::Entry::Occupied(mut chan_entry) => {
1929 if chan_entry.get().get_their_node_id() != *their_node_id {
1930 //TODO: here and below MsgHandleErrInternal, #153 case
1931 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1933 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1934 if let Some(msg) = shutdown {
1935 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1936 node_id: their_node_id.clone(),
1940 if let Some(msg) = closing_signed {
1941 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1942 node_id: their_node_id.clone(),
1946 if chan_entry.get().is_shutdown() {
1947 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1948 channel_state.short_to_id.remove(&short_id);
1950 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1951 } else { (dropped_htlcs, None) }
1953 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1956 for htlc_source in dropped_htlcs.drain(..) {
1957 // unknown_next_peer...I dunno who that is anymore....
1958 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1960 if let Some(chan) = chan_option {
1961 if let Ok(update) = self.get_channel_update(&chan) {
1962 let mut channel_state = self.channel_state.lock().unwrap();
1963 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1971 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1972 let (tx, chan_option) = {
1973 let mut channel_state_lock = self.channel_state.lock().unwrap();
1974 let channel_state = channel_state_lock.borrow_parts();
1975 match channel_state.by_id.entry(msg.channel_id.clone()) {
1976 hash_map::Entry::Occupied(mut chan_entry) => {
1977 if chan_entry.get().get_their_node_id() != *their_node_id {
1978 //TODO: here and below MsgHandleErrInternal, #153 case
1979 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1981 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1982 if let Some(msg) = closing_signed {
1983 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1984 node_id: their_node_id.clone(),
1989 // We're done with this channel, we've got a signed closing transaction and
1990 // will send the closing_signed back to the remote peer upon return. This
1991 // also implies there are no pending HTLCs left on the channel, so we can
1992 // fully delete it from tracking (the channel monitor is still around to
1993 // watch for old state broadcasts)!
1994 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1995 channel_state.short_to_id.remove(&short_id);
1997 (tx, Some(chan_entry.remove_entry().1))
1998 } else { (tx, None) }
2000 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2003 if let Some(broadcast_tx) = tx {
2004 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2006 if let Some(chan) = chan_option {
2007 if let Ok(update) = self.get_channel_update(&chan) {
2008 let mut channel_state = self.channel_state.lock().unwrap();
2009 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2017 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2018 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2019 //determine the state of the payment based on our response/if we forward anything/the time
2020 //we take to respond. We should take care to avoid allowing such an attack.
2022 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2023 //us repeatedly garbled in different ways, and compare our error messages, which are
2024 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2025 //but we should prevent it anyway.
2027 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2028 let channel_state = channel_state_lock.borrow_parts();
2030 match channel_state.by_id.entry(msg.channel_id) {
2031 hash_map::Entry::Occupied(mut chan) => {
2032 if chan.get().get_their_node_id() != *their_node_id {
2033 //TODO: here MsgHandleErrInternal, #153 case
2034 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2036 if !chan.get().is_usable() {
2037 // If the update_add is completely bogus, the call will Err and we will close,
2038 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2039 // want to reject the new HTLC and fail it backwards instead of forwarding.
2040 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2041 let chan_update = self.get_channel_update(chan.get());
2042 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2043 channel_id: msg.channel_id,
2044 htlc_id: msg.htlc_id,
2045 reason: if let Ok(update) = chan_update {
2046 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2048 // This can only happen if the channel isn't in the fully-funded
2049 // state yet, implying our counterparty is trying to route payments
2050 // over the channel back to themselves (cause no one else should
2051 // know the short_id is a lightning channel yet). We should have no
2052 // problem just calling this unknown_next_peer
2053 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2058 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2060 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2065 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2066 let mut channel_lock = self.channel_state.lock().unwrap();
2068 let channel_state = channel_lock.borrow_parts();
2069 match channel_state.by_id.entry(msg.channel_id) {
2070 hash_map::Entry::Occupied(mut chan) => {
2071 if chan.get().get_their_node_id() != *their_node_id {
2072 //TODO: here and below MsgHandleErrInternal, #153 case
2073 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2075 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2077 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2080 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2084 // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2085 // indicating that the payment itself failed
2086 fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2087 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2088 macro_rules! onion_failure_log {
2089 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2090 log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2092 ( $error_code_textual: expr, $error_code: expr ) => {
2093 log_trace!(self, "{}({})", $error_code_textual, $error_code);
2097 const BADONION: u16 = 0x8000;
2098 const PERM: u16 = 0x4000;
2099 const UPDATE: u16 = 0x1000;
2102 let mut htlc_msat = *first_hop_htlc_msat;
2104 // Handle packed channel/node updates for passing back for the route handler
2105 Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2106 if res.is_some() { return; }
2108 let incoming_htlc_msat = htlc_msat;
2109 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2110 htlc_msat = amt_to_forward;
2112 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2114 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2115 decryption_tmp.resize(packet_decrypted.len(), 0);
2116 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2117 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2118 packet_decrypted = decryption_tmp;
2120 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2122 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2123 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2124 let mut hmac = Hmac::new(Sha256::new(), &um);
2125 hmac.input(&err_packet.encode()[32..]);
2126 let mut calc_tag = [0u8; 32];
2127 hmac.raw_result(&mut calc_tag);
2129 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2130 if err_packet.failuremsg.len() < 2 {
2131 // Useless packet that we can't use but it passed HMAC, so it
2132 // definitely came from the peer in question
2133 res = Some((None, !is_from_final_node));
2135 let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2137 match error_code & 0xff {
2139 // either from an intermediate or final node
2140 // invalid_realm(PERM|1),
2141 // temporary_node_failure(NODE|2)
2142 // permanent_node_failure(PERM|NODE|2)
2143 // required_node_feature_mssing(PERM|NODE|3)
2144 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2145 node_id: route_hop.pubkey,
2146 is_permanent: error_code & PERM == PERM,
2147 }), !(error_code & PERM == PERM && is_from_final_node)));
2148 // node returning invalid_realm is removed from network_map,
2149 // although NODE flag is not set, TODO: or remove channel only?
2150 // retry payment when removed node is not a final node
2156 if is_from_final_node {
2157 let payment_retryable = match error_code {
2158 c if c == PERM|15 => false, // unknown_payment_hash
2159 c if c == PERM|16 => false, // incorrect_payment_amount
2160 17 => true, // final_expiry_too_soon
2161 18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2162 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2165 19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2166 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2170 // A final node has sent us either an invalid code or an error_code that
2171 // MUST be sent from the processing node, or the formmat of failuremsg
2172 // does not coform to the spec.
2173 // Remove it from the network map and don't may retry payment
2174 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2175 node_id: route_hop.pubkey,
2181 res = Some((None, payment_retryable));
2185 // now, error_code should be only from the intermediate nodes
2187 _c if error_code & PERM == PERM => {
2188 res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2189 short_channel_id: route_hop.short_channel_id,
2193 _c if error_code & UPDATE == UPDATE => {
2194 let offset = match error_code {
2195 c if c == UPDATE|7 => 0, // temporary_channel_failure
2196 c if c == UPDATE|11 => 8, // amount_below_minimum
2197 c if c == UPDATE|12 => 8, // fee_insufficient
2198 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2199 c if c == UPDATE|14 => 0, // expiry_too_soon
2200 c if c == UPDATE|20 => 2, // channel_disabled
2202 // node sending unknown code
2203 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2204 node_id: route_hop.pubkey,
2211 if err_packet.failuremsg.len() >= offset + 2 {
2212 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2213 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2214 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2215 // if channel_update should NOT have caused the failure:
2216 // MAY treat the channel_update as invalid.
2217 let is_chan_update_invalid = match error_code {
2218 c if c == UPDATE|7 => { // temporary_channel_failure
2221 c if c == UPDATE|11 => { // amount_below_minimum
2222 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2223 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2224 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2226 c if c == UPDATE|12 => { // fee_insufficient
2227 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2228 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) });
2229 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2230 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2232 c if c == UPDATE|13 => { // incorrect_cltv_expiry
2233 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2234 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2235 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2237 c if c == UPDATE|20 => { // channel_disabled
2238 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2239 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2240 chan_update.contents.flags & 0x01 == 0x01
2242 c if c == UPDATE|21 => true, // expiry_too_far
2243 _ => { unreachable!(); },
2246 let msg = if is_chan_update_invalid { None } else {
2247 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2251 res = Some((msg, true));
2257 _c if error_code & BADONION == BADONION => {
2260 14 => { // expiry_too_soon
2261 res = Some((None, true));
2265 // node sending unknown code
2266 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2267 node_id: route_hop.pubkey,
2276 }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2277 res.unwrap_or((None, true))
2278 } else { ((None, true)) }
2281 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2282 let mut channel_lock = self.channel_state.lock().unwrap();
2283 let channel_state = channel_lock.borrow_parts();
2284 match channel_state.by_id.entry(msg.channel_id) {
2285 hash_map::Entry::Occupied(mut chan) => {
2286 if chan.get().get_their_node_id() != *their_node_id {
2287 //TODO: here and below MsgHandleErrInternal, #153 case
2288 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2290 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2292 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2297 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2298 let mut channel_lock = self.channel_state.lock().unwrap();
2299 let channel_state = channel_lock.borrow_parts();
2300 match channel_state.by_id.entry(msg.channel_id) {
2301 hash_map::Entry::Occupied(mut chan) => {
2302 if chan.get().get_their_node_id() != *their_node_id {
2303 //TODO: here and below MsgHandleErrInternal, #153 case
2304 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2306 if (msg.failure_code & 0x8000) == 0 {
2307 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2309 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);
2312 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2316 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2317 let mut channel_state_lock = self.channel_state.lock().unwrap();
2318 let channel_state = channel_state_lock.borrow_parts();
2319 match channel_state.by_id.entry(msg.channel_id) {
2320 hash_map::Entry::Occupied(mut chan) => {
2321 if chan.get().get_their_node_id() != *their_node_id {
2322 //TODO: here and below MsgHandleErrInternal, #153 case
2323 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2325 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2326 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2327 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2328 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2329 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2331 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2332 node_id: their_node_id.clone(),
2333 msg: revoke_and_ack,
2335 if let Some(msg) = commitment_signed {
2336 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2337 node_id: their_node_id.clone(),
2338 updates: msgs::CommitmentUpdate {
2339 update_add_htlcs: Vec::new(),
2340 update_fulfill_htlcs: Vec::new(),
2341 update_fail_htlcs: Vec::new(),
2342 update_fail_malformed_htlcs: Vec::new(),
2344 commitment_signed: msg,
2348 if let Some(msg) = closing_signed {
2349 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2350 node_id: their_node_id.clone(),
2356 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2361 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2362 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2363 let mut forward_event = None;
2364 if !pending_forwards.is_empty() {
2365 let mut channel_state = self.channel_state.lock().unwrap();
2366 if channel_state.forward_htlcs.is_empty() {
2367 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));
2368 channel_state.next_forward = forward_event.unwrap();
2370 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2371 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2372 hash_map::Entry::Occupied(mut entry) => {
2373 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2375 hash_map::Entry::Vacant(entry) => {
2376 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2381 match forward_event {
2383 let mut pending_events = self.pending_events.lock().unwrap();
2384 pending_events.push(events::Event::PendingHTLCsForwardable {
2385 time_forwardable: time
2393 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2394 let (pending_forwards, mut pending_failures, short_channel_id) = {
2395 let mut channel_state_lock = self.channel_state.lock().unwrap();
2396 let channel_state = channel_state_lock.borrow_parts();
2397 match channel_state.by_id.entry(msg.channel_id) {
2398 hash_map::Entry::Occupied(mut chan) => {
2399 if chan.get().get_their_node_id() != *their_node_id {
2400 //TODO: here and below MsgHandleErrInternal, #153 case
2401 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2403 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2404 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2405 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2406 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2408 if let Some(updates) = commitment_update {
2409 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2410 node_id: their_node_id.clone(),
2414 if let Some(msg) = closing_signed {
2415 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2416 node_id: their_node_id.clone(),
2420 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2422 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2425 for failure in pending_failures.drain(..) {
2426 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2428 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2433 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2434 let mut channel_lock = self.channel_state.lock().unwrap();
2435 let channel_state = channel_lock.borrow_parts();
2436 match channel_state.by_id.entry(msg.channel_id) {
2437 hash_map::Entry::Occupied(mut chan) => {
2438 if chan.get().get_their_node_id() != *their_node_id {
2439 //TODO: here and below MsgHandleErrInternal, #153 case
2440 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2442 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2444 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2449 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2450 let mut channel_state_lock = self.channel_state.lock().unwrap();
2451 let channel_state = channel_state_lock.borrow_parts();
2453 match channel_state.by_id.entry(msg.channel_id) {
2454 hash_map::Entry::Occupied(mut chan) => {
2455 if chan.get().get_their_node_id() != *their_node_id {
2456 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2458 if !chan.get().is_usable() {
2459 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2462 let our_node_id = self.get_our_node_id();
2463 let (announcement, our_bitcoin_sig) =
2464 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2466 let were_node_one = announcement.node_id_1 == our_node_id;
2467 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2468 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2469 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2470 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2473 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2475 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2476 msg: msgs::ChannelAnnouncement {
2477 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2478 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2479 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2480 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2481 contents: announcement,
2483 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2486 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2491 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2492 let mut channel_state_lock = self.channel_state.lock().unwrap();
2493 let channel_state = channel_state_lock.borrow_parts();
2495 match channel_state.by_id.entry(msg.channel_id) {
2496 hash_map::Entry::Occupied(mut chan) => {
2497 if chan.get().get_their_node_id() != *their_node_id {
2498 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2500 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2501 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2502 if let Some(monitor) = channel_monitor {
2503 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2504 // channel_reestablish doesn't guarantee the order it returns is sensical
2505 // for the messages it returns, but if we're setting what messages to
2506 // re-transmit on monitor update success, we need to make sure it is sane.
2507 if revoke_and_ack.is_none() {
2508 order = RAACommitmentOrder::CommitmentFirst;
2510 if commitment_update.is_none() {
2511 order = RAACommitmentOrder::RevokeAndACKFirst;
2513 return_monitor_err!(self, e, channel_state, chan, order);
2514 //TODO: Resend the funding_locked if needed once we get the monitor running again
2517 if let Some(msg) = funding_locked {
2518 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2519 node_id: their_node_id.clone(),
2523 macro_rules! send_raa { () => {
2524 if let Some(msg) = revoke_and_ack {
2525 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2526 node_id: their_node_id.clone(),
2531 macro_rules! send_cu { () => {
2532 if let Some(updates) = commitment_update {
2533 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2534 node_id: their_node_id.clone(),
2540 RAACommitmentOrder::RevokeAndACKFirst => {
2544 RAACommitmentOrder::CommitmentFirst => {
2549 if let Some(msg) = shutdown {
2550 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2551 node_id: their_node_id.clone(),
2557 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2561 /// Begin Update fee process. Allowed only on an outbound channel.
2562 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2563 /// PeerManager::process_events afterwards.
2564 /// Note: This API is likely to change!
2566 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2567 let _ = self.total_consistency_lock.read().unwrap();
2569 let err: Result<(), _> = loop {
2570 let mut channel_state_lock = self.channel_state.lock().unwrap();
2571 let channel_state = channel_state_lock.borrow_parts();
2573 match channel_state.by_id.entry(channel_id) {
2574 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2575 hash_map::Entry::Occupied(mut chan) => {
2576 if !chan.get().is_outbound() {
2577 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2579 if chan.get().is_awaiting_monitor_update() {
2580 return Err(APIError::MonitorUpdateFailed);
2582 if !chan.get().is_live() {
2583 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2585 their_node_id = chan.get().get_their_node_id();
2586 if let Some((update_fee, commitment_signed, chan_monitor)) =
2587 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2589 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2592 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2593 node_id: chan.get().get_their_node_id(),
2594 updates: msgs::CommitmentUpdate {
2595 update_add_htlcs: Vec::new(),
2596 update_fulfill_htlcs: Vec::new(),
2597 update_fail_htlcs: Vec::new(),
2598 update_fail_malformed_htlcs: Vec::new(),
2599 update_fee: Some(update_fee),
2609 match handle_error!(self, err, their_node_id) {
2610 Ok(_) => unreachable!(),
2612 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2614 log_error!(self, "Got bad keys: {}!", e.err);
2615 let mut channel_state = self.channel_state.lock().unwrap();
2616 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2617 node_id: their_node_id,
2621 Err(APIError::APIMisuseError { err: e.err })
2627 impl events::MessageSendEventsProvider for ChannelManager {
2628 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2629 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2630 // user to serialize a ChannelManager with pending events in it and lose those events on
2631 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2633 //TODO: This behavior should be documented.
2634 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2635 if let Some(preimage) = htlc_update.payment_preimage {
2636 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2638 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2643 let mut ret = Vec::new();
2644 let mut channel_state = self.channel_state.lock().unwrap();
2645 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2650 impl events::EventsProvider for ChannelManager {
2651 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2652 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2653 // user to serialize a ChannelManager with pending events in it and lose those events on
2654 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2656 //TODO: This behavior should be documented.
2657 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2658 if let Some(preimage) = htlc_update.payment_preimage {
2659 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2661 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2666 let mut ret = Vec::new();
2667 let mut pending_events = self.pending_events.lock().unwrap();
2668 mem::swap(&mut ret, &mut *pending_events);
2673 impl ChainListener for ChannelManager {
2674 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2675 let _ = self.total_consistency_lock.read().unwrap();
2676 let mut failed_channels = Vec::new();
2678 let mut channel_lock = self.channel_state.lock().unwrap();
2679 let channel_state = channel_lock.borrow_parts();
2680 let short_to_id = channel_state.short_to_id;
2681 let pending_msg_events = channel_state.pending_msg_events;
2682 channel_state.by_id.retain(|_, channel| {
2683 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2684 if let Ok(Some(funding_locked)) = chan_res {
2685 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2686 node_id: channel.get_their_node_id(),
2687 msg: funding_locked,
2689 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2690 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2691 node_id: channel.get_their_node_id(),
2692 msg: announcement_sigs,
2695 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2696 } else if let Err(e) = chan_res {
2697 pending_msg_events.push(events::MessageSendEvent::HandleError {
2698 node_id: channel.get_their_node_id(),
2699 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2703 if let Some(funding_txo) = channel.get_funding_txo() {
2704 for tx in txn_matched {
2705 for inp in tx.input.iter() {
2706 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2707 if let Some(short_id) = channel.get_short_channel_id() {
2708 short_to_id.remove(&short_id);
2710 // It looks like our counterparty went on-chain. We go ahead and
2711 // broadcast our latest local state as well here, just in case its
2712 // some kind of SPV attack, though we expect these to be dropped.
2713 failed_channels.push(channel.force_shutdown());
2714 if let Ok(update) = self.get_channel_update(&channel) {
2715 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2724 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2725 if let Some(short_id) = channel.get_short_channel_id() {
2726 short_to_id.remove(&short_id);
2728 failed_channels.push(channel.force_shutdown());
2729 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2730 // the latest local tx for us, so we should skip that here (it doesn't really
2731 // hurt anything, but does make tests a bit simpler).
2732 failed_channels.last_mut().unwrap().0 = Vec::new();
2733 if let Ok(update) = self.get_channel_update(&channel) {
2734 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2743 for failure in failed_channels.drain(..) {
2744 self.finish_force_close_channel(failure);
2746 self.latest_block_height.store(height as usize, Ordering::Release);
2747 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2750 /// We force-close the channel without letting our counterparty participate in the shutdown
2751 fn block_disconnected(&self, header: &BlockHeader) {
2752 let _ = self.total_consistency_lock.read().unwrap();
2753 let mut failed_channels = Vec::new();
2755 let mut channel_lock = self.channel_state.lock().unwrap();
2756 let channel_state = channel_lock.borrow_parts();
2757 let short_to_id = channel_state.short_to_id;
2758 let pending_msg_events = channel_state.pending_msg_events;
2759 channel_state.by_id.retain(|_, v| {
2760 if v.block_disconnected(header) {
2761 if let Some(short_id) = v.get_short_channel_id() {
2762 short_to_id.remove(&short_id);
2764 failed_channels.push(v.force_shutdown());
2765 if let Ok(update) = self.get_channel_update(&v) {
2766 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2776 for failure in failed_channels.drain(..) {
2777 self.finish_force_close_channel(failure);
2779 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2780 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2784 impl ChannelMessageHandler for ChannelManager {
2785 //TODO: Handle errors and close channel (or so)
2786 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2787 let _ = self.total_consistency_lock.read().unwrap();
2788 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2791 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2792 let _ = self.total_consistency_lock.read().unwrap();
2793 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2796 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2797 let _ = self.total_consistency_lock.read().unwrap();
2798 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2801 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2802 let _ = self.total_consistency_lock.read().unwrap();
2803 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2806 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2807 let _ = self.total_consistency_lock.read().unwrap();
2808 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2811 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2812 let _ = self.total_consistency_lock.read().unwrap();
2813 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2816 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2817 let _ = self.total_consistency_lock.read().unwrap();
2818 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2821 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2822 let _ = self.total_consistency_lock.read().unwrap();
2823 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2826 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2827 let _ = self.total_consistency_lock.read().unwrap();
2828 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2831 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2832 let _ = self.total_consistency_lock.read().unwrap();
2833 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2836 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2837 let _ = self.total_consistency_lock.read().unwrap();
2838 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2841 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2842 let _ = self.total_consistency_lock.read().unwrap();
2843 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2846 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2847 let _ = self.total_consistency_lock.read().unwrap();
2848 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2851 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2852 let _ = self.total_consistency_lock.read().unwrap();
2853 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2856 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2857 let _ = self.total_consistency_lock.read().unwrap();
2858 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2861 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2862 let _ = self.total_consistency_lock.read().unwrap();
2863 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2866 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2867 let _ = self.total_consistency_lock.read().unwrap();
2868 let mut failed_channels = Vec::new();
2869 let mut failed_payments = Vec::new();
2871 let mut channel_state_lock = self.channel_state.lock().unwrap();
2872 let channel_state = channel_state_lock.borrow_parts();
2873 let short_to_id = channel_state.short_to_id;
2874 let pending_msg_events = channel_state.pending_msg_events;
2875 if no_connection_possible {
2876 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2877 channel_state.by_id.retain(|_, chan| {
2878 if chan.get_their_node_id() == *their_node_id {
2879 if let Some(short_id) = chan.get_short_channel_id() {
2880 short_to_id.remove(&short_id);
2882 failed_channels.push(chan.force_shutdown());
2883 if let Ok(update) = self.get_channel_update(&chan) {
2884 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2894 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2895 channel_state.by_id.retain(|_, chan| {
2896 if chan.get_their_node_id() == *their_node_id {
2897 //TODO: mark channel disabled (and maybe announce such after a timeout).
2898 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2899 if !failed_adds.is_empty() {
2900 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
2901 failed_payments.push((chan_update, failed_adds));
2903 if chan.is_shutdown() {
2904 if let Some(short_id) = chan.get_short_channel_id() {
2905 short_to_id.remove(&short_id);
2914 for failure in failed_channels.drain(..) {
2915 self.finish_force_close_channel(failure);
2917 for (chan_update, mut htlc_sources) in failed_payments {
2918 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2919 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2924 fn peer_connected(&self, their_node_id: &PublicKey) {
2925 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2927 let _ = self.total_consistency_lock.read().unwrap();
2928 let mut channel_state_lock = self.channel_state.lock().unwrap();
2929 let channel_state = channel_state_lock.borrow_parts();
2930 let pending_msg_events = channel_state.pending_msg_events;
2931 channel_state.by_id.retain(|_, chan| {
2932 if chan.get_their_node_id() == *their_node_id {
2933 if !chan.have_received_message() {
2934 // If we created this (outbound) channel while we were disconnected from the
2935 // peer we probably failed to send the open_channel message, which is now
2936 // lost. We can't have had anything pending related to this channel, so we just
2940 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2941 node_id: chan.get_their_node_id(),
2942 msg: chan.get_channel_reestablish(),
2948 //TODO: Also re-broadcast announcement_signatures
2951 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2952 let _ = self.total_consistency_lock.read().unwrap();
2954 if msg.channel_id == [0; 32] {
2955 for chan in self.list_channels() {
2956 if chan.remote_network_id == *their_node_id {
2957 self.force_close_channel(&chan.channel_id);
2961 self.force_close_channel(&msg.channel_id);
2966 const SERIALIZATION_VERSION: u8 = 1;
2967 const MIN_SERIALIZATION_VERSION: u8 = 1;
2969 impl Writeable for PendingForwardHTLCInfo {
2970 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2971 if let &Some(ref onion) = &self.onion_packet {
2973 onion.write(writer)?;
2977 self.incoming_shared_secret.write(writer)?;
2978 self.payment_hash.write(writer)?;
2979 self.short_channel_id.write(writer)?;
2980 self.amt_to_forward.write(writer)?;
2981 self.outgoing_cltv_value.write(writer)?;
2986 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2987 fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2988 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2990 1 => Some(msgs::OnionPacket::read(reader)?),
2991 _ => return Err(DecodeError::InvalidValue),
2993 Ok(PendingForwardHTLCInfo {
2995 incoming_shared_secret: Readable::read(reader)?,
2996 payment_hash: Readable::read(reader)?,
2997 short_channel_id: Readable::read(reader)?,
2998 amt_to_forward: Readable::read(reader)?,
2999 outgoing_cltv_value: Readable::read(reader)?,
3004 impl Writeable for HTLCFailureMsg {
3005 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3007 &HTLCFailureMsg::Relay(ref fail_msg) => {
3009 fail_msg.write(writer)?;
3011 &HTLCFailureMsg::Malformed(ref fail_msg) => {
3013 fail_msg.write(writer)?;
3020 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3021 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3022 match <u8 as Readable<R>>::read(reader)? {
3023 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3024 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3025 _ => Err(DecodeError::InvalidValue),
3030 impl Writeable for PendingHTLCStatus {
3031 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3033 &PendingHTLCStatus::Forward(ref forward_info) => {
3035 forward_info.write(writer)?;
3037 &PendingHTLCStatus::Fail(ref fail_msg) => {
3039 fail_msg.write(writer)?;
3046 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3047 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3048 match <u8 as Readable<R>>::read(reader)? {
3049 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3050 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3051 _ => Err(DecodeError::InvalidValue),
3056 impl_writeable!(HTLCPreviousHopData, 0, {
3059 incoming_packet_shared_secret
3062 impl Writeable for HTLCSource {
3063 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3065 &HTLCSource::PreviousHopData(ref hop_data) => {
3067 hop_data.write(writer)?;
3069 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3071 route.write(writer)?;
3072 session_priv.write(writer)?;
3073 first_hop_htlc_msat.write(writer)?;
3080 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3081 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3082 match <u8 as Readable<R>>::read(reader)? {
3083 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3084 1 => Ok(HTLCSource::OutboundRoute {
3085 route: Readable::read(reader)?,
3086 session_priv: Readable::read(reader)?,
3087 first_hop_htlc_msat: Readable::read(reader)?,
3089 _ => Err(DecodeError::InvalidValue),
3094 impl Writeable for HTLCFailReason {
3095 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3097 &HTLCFailReason::ErrorPacket { ref err } => {
3101 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3103 failure_code.write(writer)?;
3104 data.write(writer)?;
3111 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3112 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3113 match <u8 as Readable<R>>::read(reader)? {
3114 0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3115 1 => Ok(HTLCFailReason::Reason {
3116 failure_code: Readable::read(reader)?,
3117 data: Readable::read(reader)?,
3119 _ => Err(DecodeError::InvalidValue),
3124 impl_writeable!(HTLCForwardInfo, 0, {
3125 prev_short_channel_id,
3130 impl Writeable for ChannelManager {
3131 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3132 let _ = self.total_consistency_lock.write().unwrap();
3134 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3135 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3137 self.genesis_hash.write(writer)?;
3138 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3139 self.last_block_hash.lock().unwrap().write(writer)?;
3141 let channel_state = self.channel_state.lock().unwrap();
3142 let mut unfunded_channels = 0;
3143 for (_, channel) in channel_state.by_id.iter() {
3144 if !channel.is_funding_initiated() {
3145 unfunded_channels += 1;
3148 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3149 for (_, channel) in channel_state.by_id.iter() {
3150 if channel.is_funding_initiated() {
3151 channel.write(writer)?;
3155 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3156 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3157 short_channel_id.write(writer)?;
3158 (pending_forwards.len() as u64).write(writer)?;
3159 for forward in pending_forwards {
3160 forward.write(writer)?;
3164 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3165 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3166 payment_hash.write(writer)?;
3167 (previous_hops.len() as u64).write(writer)?;
3168 for previous_hop in previous_hops {
3169 previous_hop.write(writer)?;
3177 /// Arguments for the creation of a ChannelManager that are not deserialized.
3179 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3181 /// 1) Deserialize all stored ChannelMonitors.
3182 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3183 /// ChannelManager)>::read(reader, args).
3184 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3185 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3186 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3187 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3188 /// 4) Reconnect blocks on your ChannelMonitors.
3189 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3190 /// 6) Disconnect/connect blocks on the ChannelManager.
3191 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3192 /// automatically as it does in ChannelManager::new()).
3193 pub struct ChannelManagerReadArgs<'a> {
3194 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3195 /// deserialization.
3196 pub keys_manager: Arc<KeysInterface>,
3198 /// The fee_estimator for use in the ChannelManager in the future.
3200 /// No calls to the FeeEstimator will be made during deserialization.
3201 pub fee_estimator: Arc<FeeEstimator>,
3202 /// The ManyChannelMonitor for use in the ChannelManager in the future.
3204 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3205 /// you have deserialized ChannelMonitors separately and will add them to your
3206 /// ManyChannelMonitor after deserializing this ChannelManager.
3207 pub monitor: Arc<ManyChannelMonitor>,
3208 /// The ChainWatchInterface for use in the ChannelManager in the future.
3210 /// No calls to the ChainWatchInterface will be made during deserialization.
3211 pub chain_monitor: Arc<ChainWatchInterface>,
3212 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3213 /// used to broadcast the latest local commitment transactions of channels which must be
3214 /// force-closed during deserialization.
3215 pub tx_broadcaster: Arc<BroadcasterInterface>,
3216 /// The Logger for use in the ChannelManager and which may be used to log information during
3217 /// deserialization.
3218 pub logger: Arc<Logger>,
3219 /// Default settings used for new channels. Any existing channels will continue to use the
3220 /// runtime settings which were stored when the ChannelManager was serialized.
3221 pub default_config: UserConfig,
3223 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3224 /// value.get_funding_txo() should be the key).
3226 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3227 /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3228 /// is true for missing channels as well. If there is a monitor missing for which we find
3229 /// channel data Err(DecodeError::InvalidValue) will be returned.
3231 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3233 pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3236 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3237 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3238 let _ver: u8 = Readable::read(reader)?;
3239 let min_ver: u8 = Readable::read(reader)?;
3240 if min_ver > SERIALIZATION_VERSION {
3241 return Err(DecodeError::UnknownVersion);
3244 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3245 let latest_block_height: u32 = Readable::read(reader)?;
3246 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3248 let mut closed_channels = Vec::new();
3250 let channel_count: u64 = Readable::read(reader)?;
3251 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3252 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3253 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3254 for _ in 0..channel_count {
3255 let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3256 if channel.last_block_connected != last_block_hash {
3257 return Err(DecodeError::InvalidValue);
3260 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3261 funding_txo_set.insert(funding_txo.clone());
3262 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3263 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3264 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3265 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3266 let mut force_close_res = channel.force_shutdown();
3267 force_close_res.0 = monitor.get_latest_local_commitment_txn();
3268 closed_channels.push(force_close_res);
3270 if let Some(short_channel_id) = channel.get_short_channel_id() {
3271 short_to_id.insert(short_channel_id, channel.channel_id());
3273 by_id.insert(channel.channel_id(), channel);
3276 return Err(DecodeError::InvalidValue);
3280 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3281 if !funding_txo_set.contains(funding_txo) {
3282 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3286 let forward_htlcs_count: u64 = Readable::read(reader)?;
3287 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3288 for _ in 0..forward_htlcs_count {
3289 let short_channel_id = Readable::read(reader)?;
3290 let pending_forwards_count: u64 = Readable::read(reader)?;
3291 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3292 for _ in 0..pending_forwards_count {
3293 pending_forwards.push(Readable::read(reader)?);
3295 forward_htlcs.insert(short_channel_id, pending_forwards);
3298 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3299 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3300 for _ in 0..claimable_htlcs_count {
3301 let payment_hash = Readable::read(reader)?;
3302 let previous_hops_len: u64 = Readable::read(reader)?;
3303 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3304 for _ in 0..previous_hops_len {
3305 previous_hops.push(Readable::read(reader)?);
3307 claimable_htlcs.insert(payment_hash, previous_hops);
3310 let channel_manager = ChannelManager {
3312 fee_estimator: args.fee_estimator,
3313 monitor: args.monitor,
3314 chain_monitor: args.chain_monitor,
3315 tx_broadcaster: args.tx_broadcaster,
3317 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3318 last_block_hash: Mutex::new(last_block_hash),
3319 secp_ctx: Secp256k1::new(),
3321 channel_state: Mutex::new(ChannelHolder {
3324 next_forward: Instant::now(),
3327 pending_msg_events: Vec::new(),
3329 our_network_key: args.keys_manager.get_node_secret(),
3331 pending_events: Mutex::new(Vec::new()),
3332 total_consistency_lock: RwLock::new(()),
3333 keys_manager: args.keys_manager,
3334 logger: args.logger,
3335 default_configuration: args.default_config,
3338 for close_res in closed_channels.drain(..) {
3339 channel_manager.finish_force_close_channel(close_res);
3340 //TODO: Broadcast channel update for closed channels, but only after we've made a
3341 //connection or two.
3344 Ok((last_block_hash.clone(), channel_manager))
3350 use chain::chaininterface;
3351 use chain::transaction::OutPoint;
3352 use chain::chaininterface::{ChainListener, ChainWatchInterface};
3353 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3354 use chain::keysinterface;
3355 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3356 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder};
3357 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3358 use ln::router::{Route, RouteHop, Router};
3360 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3361 use util::test_utils;
3362 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3363 use util::errors::APIError;
3364 use util::logger::Logger;
3365 use util::ser::{Writeable, Writer, ReadableArgs};
3366 use util::config::UserConfig;
3368 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3369 use bitcoin::util::bip143;
3370 use bitcoin::util::address::Address;
3371 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3372 use bitcoin::blockdata::block::{Block, BlockHeader};
3373 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3374 use bitcoin::blockdata::script::{Builder, Script};
3375 use bitcoin::blockdata::opcodes;
3376 use bitcoin::blockdata::constants::genesis_block;
3377 use bitcoin::network::constants::Network;
3381 use secp256k1::{Secp256k1, Message};
3382 use secp256k1::key::{PublicKey,SecretKey};
3384 use crypto::sha2::Sha256;
3385 use crypto::digest::Digest;
3387 use rand::{thread_rng,Rng};
3389 use std::cell::RefCell;
3390 use std::collections::{BTreeSet, HashMap};
3391 use std::default::Default;
3393 use std::sync::{Arc, Mutex};
3394 use std::sync::atomic::Ordering;
3395 use std::time::Instant;
3398 fn build_test_onion_keys() -> Vec<OnionKeys> {
3399 // Keys from BOLT 4, used in both test vector tests
3400 let secp_ctx = Secp256k1::new();
3405 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3406 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
3409 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3410 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
3413 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3414 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
3417 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3418 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
3421 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3422 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3427 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3429 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3430 assert_eq!(onion_keys.len(), route.hops.len());
3435 fn onion_vectors() {
3436 // Packet creation test vectors from BOLT 4
3437 let onion_keys = build_test_onion_keys();
3439 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3440 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3441 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3442 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3443 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3445 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3446 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3447 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3448 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3449 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3451 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3452 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3453 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3454 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3455 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3457 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3458 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3459 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3460 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3461 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3463 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3464 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3465 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3466 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3467 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3469 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3470 let payloads = vec!(
3471 msgs::OnionHopData {
3473 data: msgs::OnionRealm0HopData {
3474 short_channel_id: 0,
3476 outgoing_cltv_value: 0,
3480 msgs::OnionHopData {
3482 data: msgs::OnionRealm0HopData {
3483 short_channel_id: 0x0101010101010101,
3484 amt_to_forward: 0x0100000001,
3485 outgoing_cltv_value: 0,
3489 msgs::OnionHopData {
3491 data: msgs::OnionRealm0HopData {
3492 short_channel_id: 0x0202020202020202,
3493 amt_to_forward: 0x0200000002,
3494 outgoing_cltv_value: 0,
3498 msgs::OnionHopData {
3500 data: msgs::OnionRealm0HopData {
3501 short_channel_id: 0x0303030303030303,
3502 amt_to_forward: 0x0300000003,
3503 outgoing_cltv_value: 0,
3507 msgs::OnionHopData {
3509 data: msgs::OnionRealm0HopData {
3510 short_channel_id: 0x0404040404040404,
3511 amt_to_forward: 0x0400000004,
3512 outgoing_cltv_value: 0,
3518 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
3519 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3521 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3525 fn test_failure_packet_onion() {
3526 // Returning Errors test vectors from BOLT 4
3528 let onion_keys = build_test_onion_keys();
3529 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3530 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3532 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3533 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3535 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3536 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3538 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3539 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3541 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3542 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3544 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3545 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3548 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3549 assert!(chain.does_match_tx(tx));
3550 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3551 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3553 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3554 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3559 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3560 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3561 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3562 node: Arc<ChannelManager>,
3564 node_seed: [u8; 32],
3565 network_payment_count: Rc<RefCell<u8>>,
3566 network_chan_count: Rc<RefCell<u32>>,
3568 impl Drop for Node {
3569 fn drop(&mut self) {
3570 if !::std::thread::panicking() {
3571 // Check that we processed all pending events
3572 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3573 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3574 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3579 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3580 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3583 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) {
3584 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3585 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3586 (announcement, as_update, bs_update, channel_id, tx)
3589 macro_rules! get_revoke_commit_msgs {
3590 ($node: expr, $node_id: expr) => {
3592 let events = $node.node.get_and_clear_pending_msg_events();
3593 assert_eq!(events.len(), 2);
3595 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3596 assert_eq!(*node_id, $node_id);
3599 _ => panic!("Unexpected event"),
3600 }, match events[1] {
3601 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3602 assert_eq!(*node_id, $node_id);
3603 assert!(updates.update_add_htlcs.is_empty());
3604 assert!(updates.update_fulfill_htlcs.is_empty());
3605 assert!(updates.update_fail_htlcs.is_empty());
3606 assert!(updates.update_fail_malformed_htlcs.is_empty());
3607 assert!(updates.update_fee.is_none());
3608 updates.commitment_signed.clone()
3610 _ => panic!("Unexpected event"),
3616 macro_rules! get_event_msg {
3617 ($node: expr, $event_type: path, $node_id: expr) => {
3619 let events = $node.node.get_and_clear_pending_msg_events();
3620 assert_eq!(events.len(), 1);
3622 $event_type { ref node_id, ref msg } => {
3623 assert_eq!(*node_id, $node_id);
3626 _ => panic!("Unexpected event"),
3632 macro_rules! get_htlc_update_msgs {
3633 ($node: expr, $node_id: expr) => {
3635 let events = $node.node.get_and_clear_pending_msg_events();
3636 assert_eq!(events.len(), 1);
3638 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3639 assert_eq!(*node_id, $node_id);
3642 _ => panic!("Unexpected event"),
3648 macro_rules! get_feerate {
3649 ($node: expr, $channel_id: expr) => {
3651 let chan_lock = $node.node.channel_state.lock().unwrap();
3652 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3659 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3660 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3661 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();
3662 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();
3664 let chan_id = *node_a.network_chan_count.borrow();
3668 let events_2 = node_a.node.get_and_clear_pending_events();
3669 assert_eq!(events_2.len(), 1);
3671 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3672 assert_eq!(*channel_value_satoshis, channel_value);
3673 assert_eq!(user_channel_id, 42);
3675 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3676 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3678 funding_output = OutPoint::new(tx.txid(), 0);
3680 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3681 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3682 assert_eq!(added_monitors.len(), 1);
3683 assert_eq!(added_monitors[0].0, funding_output);
3684 added_monitors.clear();
3686 _ => panic!("Unexpected event"),
3689 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();
3691 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3692 assert_eq!(added_monitors.len(), 1);
3693 assert_eq!(added_monitors[0].0, funding_output);
3694 added_monitors.clear();
3697 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();
3699 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3700 assert_eq!(added_monitors.len(), 1);
3701 assert_eq!(added_monitors[0].0, funding_output);
3702 added_monitors.clear();
3705 let events_4 = node_a.node.get_and_clear_pending_events();
3706 assert_eq!(events_4.len(), 1);
3708 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3709 assert_eq!(user_channel_id, 42);
3710 assert_eq!(*funding_txo, funding_output);
3712 _ => panic!("Unexpected event"),
3718 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3719 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3720 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();
3724 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3725 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3726 assert_eq!(events_6.len(), 2);
3727 ((match events_6[0] {
3728 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3729 channel_id = msg.channel_id.clone();
3730 assert_eq!(*node_id, node_b.node.get_our_node_id());
3733 _ => panic!("Unexpected event"),
3734 }, match events_6[1] {
3735 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3736 assert_eq!(*node_id, node_b.node.get_our_node_id());
3739 _ => panic!("Unexpected event"),
3743 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) {
3744 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3745 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3749 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) {
3750 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3751 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3752 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3754 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3755 assert_eq!(events_7.len(), 1);
3756 let (announcement, bs_update) = match events_7[0] {
3757 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3760 _ => panic!("Unexpected event"),
3763 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3764 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3765 assert_eq!(events_8.len(), 1);
3766 let as_update = match events_8[0] {
3767 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3768 assert!(*announcement == *msg);
3771 _ => panic!("Unexpected event"),
3774 *node_a.network_chan_count.borrow_mut() += 1;
3776 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3779 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3780 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3783 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) {
3784 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3786 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3787 node.router.handle_channel_update(&chan_announcement.1).unwrap();
3788 node.router.handle_channel_update(&chan_announcement.2).unwrap();
3790 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3793 macro_rules! check_spends {
3794 ($tx: expr, $spends_tx: expr) => {
3796 let mut funding_tx_map = HashMap::new();
3797 let spends_tx = $spends_tx;
3798 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3799 $tx.verify(&funding_tx_map).unwrap();
3804 macro_rules! get_closing_signed_broadcast {
3805 ($node: expr, $dest_pubkey: expr) => {
3807 let events = $node.get_and_clear_pending_msg_events();
3808 assert!(events.len() == 1 || events.len() == 2);
3809 (match events[events.len() - 1] {
3810 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3811 assert_eq!(msg.contents.flags & 2, 2);
3814 _ => panic!("Unexpected event"),
3815 }, if events.len() == 2 {
3817 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3818 assert_eq!(*node_id, $dest_pubkey);
3821 _ => panic!("Unexpected event"),
3828 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) {
3829 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) };
3830 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3833 node_a.close_channel(channel_id).unwrap();
3834 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3836 let events_1 = node_b.get_and_clear_pending_msg_events();
3837 assert!(events_1.len() >= 1);
3838 let shutdown_b = match events_1[0] {
3839 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3840 assert_eq!(node_id, &node_a.get_our_node_id());
3843 _ => panic!("Unexpected event"),
3846 let closing_signed_b = if !close_inbound_first {
3847 assert_eq!(events_1.len(), 1);
3850 Some(match events_1[1] {
3851 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3852 assert_eq!(node_id, &node_a.get_our_node_id());
3855 _ => panic!("Unexpected event"),
3859 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3860 let (as_update, bs_update) = if close_inbound_first {
3861 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3862 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3863 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3864 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3865 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3867 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3868 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3869 assert!(none_b.is_none());
3870 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3871 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3872 (as_update, bs_update)
3874 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3876 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3877 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3878 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3879 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3881 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3882 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3883 assert!(none_a.is_none());
3884 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3885 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3886 (as_update, bs_update)
3888 assert_eq!(tx_a, tx_b);
3889 check_spends!(tx_a, funding_tx);
3891 (as_update, bs_update, tx_a)
3896 msgs: Vec<msgs::UpdateAddHTLC>,
3897 commitment_msg: msgs::CommitmentSigned,
3900 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3901 assert!(updates.update_fulfill_htlcs.is_empty());
3902 assert!(updates.update_fail_htlcs.is_empty());
3903 assert!(updates.update_fail_malformed_htlcs.is_empty());
3904 assert!(updates.update_fee.is_none());
3905 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3908 fn from_event(event: MessageSendEvent) -> SendEvent {
3910 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3911 _ => panic!("Unexpected event type!"),
3915 fn from_node(node: &Node) -> SendEvent {
3916 let mut events = node.node.get_and_clear_pending_msg_events();
3917 assert_eq!(events.len(), 1);
3918 SendEvent::from_event(events.pop().unwrap())
3922 macro_rules! check_added_monitors {
3923 ($node: expr, $count: expr) => {
3925 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3926 assert_eq!(added_monitors.len(), $count);
3927 added_monitors.clear();
3932 macro_rules! commitment_signed_dance {
3933 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3935 check_added_monitors!($node_a, 0);
3936 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3937 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3938 check_added_monitors!($node_a, 1);
3939 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3942 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3944 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3945 check_added_monitors!($node_b, 0);
3946 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3947 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3948 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3949 check_added_monitors!($node_b, 1);
3950 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3951 let (bs_revoke_and_ack, extra_msg_option) = {
3952 let events = $node_b.node.get_and_clear_pending_msg_events();
3953 assert!(events.len() <= 2);
3955 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3956 assert_eq!(*node_id, $node_a.node.get_our_node_id());
3959 _ => panic!("Unexpected event"),
3960 }, events.get(1).map(|e| e.clone()))
3962 check_added_monitors!($node_b, 1);
3963 if $fail_backwards {
3964 assert!($node_a.node.get_and_clear_pending_events().is_empty());
3965 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3967 (extra_msg_option, bs_revoke_and_ack)
3970 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3972 check_added_monitors!($node_a, 0);
3973 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3974 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3975 check_added_monitors!($node_a, 1);
3976 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3977 assert!(extra_msg_option.is_none());
3981 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3983 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3984 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3986 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3987 if $fail_backwards {
3988 assert_eq!(added_monitors.len(), 2);
3989 assert!(added_monitors[0].0 != added_monitors[1].0);
3991 assert_eq!(added_monitors.len(), 1);
3993 added_monitors.clear();
3998 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4000 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4003 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4005 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4006 if $fail_backwards {
4007 let channel_state = $node_a.node.channel_state.lock().unwrap();
4008 assert_eq!(channel_state.pending_msg_events.len(), 1);
4009 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4010 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4011 } else { panic!("Unexpected event"); }
4013 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4019 macro_rules! get_payment_preimage_hash {
4022 let payment_preimage = [*$node.network_payment_count.borrow(); 32];
4023 *$node.network_payment_count.borrow_mut() += 1;
4024 let mut payment_hash = [0; 32];
4025 let mut sha = Sha256::new();
4026 sha.input(&payment_preimage[..]);
4027 sha.result(&mut payment_hash);
4028 (payment_preimage, payment_hash)
4033 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
4034 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4036 let mut payment_event = {
4037 origin_node.node.send_payment(route, our_payment_hash).unwrap();
4038 check_added_monitors!(origin_node, 1);
4040 let mut events = origin_node.node.get_and_clear_pending_msg_events();
4041 assert_eq!(events.len(), 1);
4042 SendEvent::from_event(events.remove(0))
4044 let mut prev_node = origin_node;
4046 for (idx, &node) in expected_route.iter().enumerate() {
4047 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4049 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4050 check_added_monitors!(node, 0);
4051 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4053 let events_1 = node.node.get_and_clear_pending_events();
4054 assert_eq!(events_1.len(), 1);
4056 Event::PendingHTLCsForwardable { .. } => { },
4057 _ => panic!("Unexpected event"),
4060 node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4061 node.node.process_pending_htlc_forwards();
4063 if idx == expected_route.len() - 1 {
4064 let events_2 = node.node.get_and_clear_pending_events();
4065 assert_eq!(events_2.len(), 1);
4067 Event::PaymentReceived { ref payment_hash, amt } => {
4068 assert_eq!(our_payment_hash, *payment_hash);
4069 assert_eq!(amt, recv_value);
4071 _ => panic!("Unexpected event"),
4074 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4075 assert_eq!(events_2.len(), 1);
4076 check_added_monitors!(node, 1);
4077 payment_event = SendEvent::from_event(events_2.remove(0));
4078 assert_eq!(payment_event.msgs.len(), 1);
4084 (our_payment_preimage, our_payment_hash)
4087 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
4088 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4089 check_added_monitors!(expected_route.last().unwrap(), 1);
4091 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4092 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4093 macro_rules! get_next_msgs {
4096 let events = $node.node.get_and_clear_pending_msg_events();
4097 assert_eq!(events.len(), 1);
4099 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 } } => {
4100 assert!(update_add_htlcs.is_empty());
4101 assert_eq!(update_fulfill_htlcs.len(), 1);
4102 assert!(update_fail_htlcs.is_empty());
4103 assert!(update_fail_malformed_htlcs.is_empty());
4104 assert!(update_fee.is_none());
4105 expected_next_node = node_id.clone();
4106 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4108 _ => panic!("Unexpected event"),
4114 macro_rules! last_update_fulfill_dance {
4115 ($node: expr, $prev_node: expr) => {
4117 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4118 check_added_monitors!($node, 0);
4119 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4120 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4124 macro_rules! mid_update_fulfill_dance {
4125 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4127 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4128 check_added_monitors!($node, 1);
4129 let new_next_msgs = if $new_msgs {
4130 get_next_msgs!($node)
4132 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4135 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4136 next_msgs = new_next_msgs;
4141 let mut prev_node = expected_route.last().unwrap();
4142 for (idx, node) in expected_route.iter().rev().enumerate() {
4143 assert_eq!(expected_next_node, node.node.get_our_node_id());
4144 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4145 if next_msgs.is_some() {
4146 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4147 } else if update_next_msgs {
4148 next_msgs = get_next_msgs!(node);
4150 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4152 if !skip_last && idx == expected_route.len() - 1 {
4153 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4160 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4161 let events = origin_node.node.get_and_clear_pending_events();
4162 assert_eq!(events.len(), 1);
4164 Event::PaymentSent { payment_preimage } => {
4165 assert_eq!(payment_preimage, our_payment_preimage);
4167 _ => panic!("Unexpected event"),
4172 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
4173 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4176 const TEST_FINAL_CLTV: u32 = 32;
4178 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
4179 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();
4180 assert_eq!(route.hops.len(), expected_route.len());
4181 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4182 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4185 send_along_route(origin_node, route, expected_route, recv_value)
4188 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4189 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
4190 assert_eq!(route.hops.len(), expected_route.len());
4191 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4192 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4195 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4197 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4199 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4200 _ => panic!("Unknown error variants"),
4204 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4205 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4206 claim_payment(&origin, expected_route, our_payment_preimage);
4209 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
4210 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4211 check_added_monitors!(expected_route.last().unwrap(), 1);
4213 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4214 macro_rules! update_fail_dance {
4215 ($node: expr, $prev_node: expr, $last_node: expr) => {
4217 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4218 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4223 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4224 let mut prev_node = expected_route.last().unwrap();
4225 for (idx, node) in expected_route.iter().rev().enumerate() {
4226 assert_eq!(expected_next_node, node.node.get_our_node_id());
4227 if next_msgs.is_some() {
4228 // We may be the "last node" for the purpose of the commitment dance if we're
4229 // skipping the last node (implying it is disconnected) and we're the
4230 // second-to-last node!
4231 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4234 let events = node.node.get_and_clear_pending_msg_events();
4235 if !skip_last || idx != expected_route.len() - 1 {
4236 assert_eq!(events.len(), 1);
4238 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 } } => {
4239 assert!(update_add_htlcs.is_empty());
4240 assert!(update_fulfill_htlcs.is_empty());
4241 assert_eq!(update_fail_htlcs.len(), 1);
4242 assert!(update_fail_malformed_htlcs.is_empty());
4243 assert!(update_fee.is_none());
4244 expected_next_node = node_id.clone();
4245 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4247 _ => panic!("Unexpected event"),
4250 assert!(events.is_empty());
4252 if !skip_last && idx == expected_route.len() - 1 {
4253 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4260 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4262 let events = origin_node.node.get_and_clear_pending_events();
4263 assert_eq!(events.len(), 1);
4265 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4266 assert_eq!(payment_hash, our_payment_hash);
4267 assert!(rejected_by_dest);
4269 _ => panic!("Unexpected event"),
4274 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
4275 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4278 fn create_network(node_count: usize) -> Vec<Node> {
4279 let mut nodes = Vec::new();
4280 let mut rng = thread_rng();
4281 let secp_ctx = Secp256k1::new();
4282 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
4284 let chan_count = Rc::new(RefCell::new(0));
4285 let payment_count = Rc::new(RefCell::new(0));
4287 for _ in 0..node_count {
4288 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4289 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4290 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4291 let mut seed = [0; 32];
4292 rng.fill_bytes(&mut seed);
4293 let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4294 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4295 let mut config = UserConfig::new();
4296 config.channel_options.announced_channel = true;
4297 config.channel_limits.force_announced_channel_preference = false;
4298 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();
4299 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4300 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4301 network_payment_count: payment_count.clone(),
4302 network_chan_count: chan_count.clone(),
4310 fn test_async_inbound_update_fee() {
4311 let mut nodes = create_network(2);
4312 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4313 let channel_id = chan.2;
4316 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4320 // send (1) commitment_signed -.
4321 // <- update_add_htlc/commitment_signed
4322 // send (2) RAA (awaiting remote revoke) -.
4323 // (1) commitment_signed is delivered ->
4324 // .- send (3) RAA (awaiting remote revoke)
4325 // (2) RAA is delivered ->
4326 // .- send (4) commitment_signed
4327 // <- (3) RAA is delivered
4328 // send (5) commitment_signed -.
4329 // <- (4) commitment_signed is delivered
4331 // (5) commitment_signed is delivered ->
4333 // (6) RAA is delivered ->
4335 // First nodes[0] generates an update_fee
4336 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4337 check_added_monitors!(nodes[0], 1);
4339 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4340 assert_eq!(events_0.len(), 1);
4341 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4342 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4343 (update_fee.as_ref(), commitment_signed)
4345 _ => panic!("Unexpected event"),
4348 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4350 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4351 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4352 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();
4353 check_added_monitors!(nodes[1], 1);
4355 let payment_event = {
4356 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4357 assert_eq!(events_1.len(), 1);
4358 SendEvent::from_event(events_1.remove(0))
4360 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4361 assert_eq!(payment_event.msgs.len(), 1);
4363 // ...now when the messages get delivered everyone should be happy
4364 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4365 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4366 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4367 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4368 check_added_monitors!(nodes[0], 1);
4370 // deliver(1), generate (3):
4371 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4372 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4373 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4374 check_added_monitors!(nodes[1], 1);
4376 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4377 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4378 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4379 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4380 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4381 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4382 assert!(bs_update.update_fee.is_none()); // (4)
4383 check_added_monitors!(nodes[1], 1);
4385 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4386 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4387 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4388 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4389 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4390 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4391 assert!(as_update.update_fee.is_none()); // (5)
4392 check_added_monitors!(nodes[0], 1);
4394 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4395 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4396 // only (6) so get_event_msg's assert(len == 1) passes
4397 check_added_monitors!(nodes[0], 1);
4399 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4400 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4401 check_added_monitors!(nodes[1], 1);
4403 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4404 check_added_monitors!(nodes[0], 1);
4406 let events_2 = nodes[0].node.get_and_clear_pending_events();
4407 assert_eq!(events_2.len(), 1);
4409 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4410 _ => panic!("Unexpected event"),
4413 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4414 check_added_monitors!(nodes[1], 1);
4418 fn test_update_fee_unordered_raa() {
4419 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4420 // crash in an earlier version of the update_fee patch)
4421 let mut nodes = create_network(2);
4422 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4423 let channel_id = chan.2;
4426 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4428 // First nodes[0] generates an update_fee
4429 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4430 check_added_monitors!(nodes[0], 1);
4432 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4433 assert_eq!(events_0.len(), 1);
4434 let update_msg = match events_0[0] { // (1)
4435 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4438 _ => panic!("Unexpected event"),
4441 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4443 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4444 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4445 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();
4446 check_added_monitors!(nodes[1], 1);
4448 let payment_event = {
4449 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4450 assert_eq!(events_1.len(), 1);
4451 SendEvent::from_event(events_1.remove(0))
4453 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4454 assert_eq!(payment_event.msgs.len(), 1);
4456 // ...now when the messages get delivered everyone should be happy
4457 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4458 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4459 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4460 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4461 check_added_monitors!(nodes[0], 1);
4463 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4464 check_added_monitors!(nodes[1], 1);
4466 // We can't continue, sadly, because our (1) now has a bogus signature
4470 fn test_multi_flight_update_fee() {
4471 let nodes = create_network(2);
4472 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4473 let channel_id = chan.2;
4476 // update_fee/commitment_signed ->
4477 // .- send (1) RAA and (2) commitment_signed
4478 // update_fee (never committed) ->
4479 // (3) update_fee ->
4480 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4481 // don't track which updates correspond to which revoke_and_ack responses so we're in
4482 // AwaitingRAA mode and will not generate the update_fee yet.
4483 // <- (1) RAA delivered
4484 // (3) is generated and send (4) CS -.
4485 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4486 // know the per_commitment_point to use for it.
4487 // <- (2) commitment_signed delivered
4488 // revoke_and_ack ->
4489 // B should send no response here
4490 // (4) commitment_signed delivered ->
4491 // <- RAA/commitment_signed delivered
4492 // revoke_and_ack ->
4494 // First nodes[0] generates an update_fee
4495 let initial_feerate = get_feerate!(nodes[0], channel_id);
4496 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4497 check_added_monitors!(nodes[0], 1);
4499 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4500 assert_eq!(events_0.len(), 1);
4501 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4502 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4503 (update_fee.as_ref().unwrap(), commitment_signed)
4505 _ => panic!("Unexpected event"),
4508 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4509 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4510 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4511 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4512 check_added_monitors!(nodes[1], 1);
4514 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4516 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4517 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4518 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4520 // Create the (3) update_fee message that nodes[0] will generate before it does...
4521 let mut update_msg_2 = msgs::UpdateFee {
4522 channel_id: update_msg_1.channel_id.clone(),
4523 feerate_per_kw: (initial_feerate + 30) as u32,
4526 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4528 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4530 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4532 // Deliver (1), generating (3) and (4)
4533 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4534 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4535 check_added_monitors!(nodes[0], 1);
4536 assert!(as_second_update.update_add_htlcs.is_empty());
4537 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4538 assert!(as_second_update.update_fail_htlcs.is_empty());
4539 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4540 // Check that the update_fee newly generated matches what we delivered:
4541 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4542 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4544 // Deliver (2) commitment_signed
4545 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4546 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4547 check_added_monitors!(nodes[0], 1);
4548 // No commitment_signed so get_event_msg's assert(len == 1) passes
4550 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4551 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4552 check_added_monitors!(nodes[1], 1);
4555 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4556 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4557 check_added_monitors!(nodes[1], 1);
4559 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4560 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4561 check_added_monitors!(nodes[0], 1);
4563 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4564 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4565 // No commitment_signed so get_event_msg's assert(len == 1) passes
4566 check_added_monitors!(nodes[0], 1);
4568 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4569 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4570 check_added_monitors!(nodes[1], 1);
4574 fn test_update_fee_vanilla() {
4575 let nodes = create_network(2);
4576 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4577 let channel_id = chan.2;
4579 let feerate = get_feerate!(nodes[0], channel_id);
4580 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4581 check_added_monitors!(nodes[0], 1);
4583 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4584 assert_eq!(events_0.len(), 1);
4585 let (update_msg, commitment_signed) = match events_0[0] {
4586 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 } } => {
4587 (update_fee.as_ref(), commitment_signed)
4589 _ => panic!("Unexpected event"),
4591 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4593 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4594 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4595 check_added_monitors!(nodes[1], 1);
4597 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4598 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4599 check_added_monitors!(nodes[0], 1);
4601 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4602 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4603 // No commitment_signed so get_event_msg's assert(len == 1) passes
4604 check_added_monitors!(nodes[0], 1);
4606 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4607 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4608 check_added_monitors!(nodes[1], 1);
4612 fn test_update_fee_that_funder_cannot_afford() {
4613 let nodes = create_network(2);
4614 let channel_value = 1888;
4615 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4616 let channel_id = chan.2;
4619 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4620 check_added_monitors!(nodes[0], 1);
4621 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4623 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4625 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4627 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4628 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4630 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4631 let chan = chan_lock.by_id.get(&channel_id).unwrap();
4633 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4634 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4635 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4636 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4637 actual_fee = channel_value - actual_fee;
4638 assert_eq!(total_fee, actual_fee);
4641 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4642 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4643 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4644 check_added_monitors!(nodes[0], 1);
4646 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4648 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4650 //While producing the commitment_signed response after handling a received update_fee request the
4651 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4652 //Should produce and error.
4653 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4655 assert!(match err.err {
4656 "Funding remote cannot afford proposed new fee" => true,
4660 //clear the message we could not handle
4661 nodes[1].node.get_and_clear_pending_msg_events();
4665 fn test_update_fee_with_fundee_update_add_htlc() {
4666 let mut nodes = create_network(2);
4667 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4668 let channel_id = chan.2;
4671 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4673 let feerate = get_feerate!(nodes[0], channel_id);
4674 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4675 check_added_monitors!(nodes[0], 1);
4677 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4678 assert_eq!(events_0.len(), 1);
4679 let (update_msg, commitment_signed) = match events_0[0] {
4680 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 } } => {
4681 (update_fee.as_ref(), commitment_signed)
4683 _ => panic!("Unexpected event"),
4685 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4686 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4687 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4688 check_added_monitors!(nodes[1], 1);
4690 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4692 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4694 // nothing happens since node[1] is in AwaitingRemoteRevoke
4695 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4697 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4698 assert_eq!(added_monitors.len(), 0);
4699 added_monitors.clear();
4701 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4702 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4703 // node[1] has nothing to do
4705 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4706 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4707 check_added_monitors!(nodes[0], 1);
4709 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4710 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4711 // No commitment_signed so get_event_msg's assert(len == 1) passes
4712 check_added_monitors!(nodes[0], 1);
4713 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4714 check_added_monitors!(nodes[1], 1);
4715 // AwaitingRemoteRevoke ends here
4717 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4718 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4719 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4720 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4721 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4722 assert_eq!(commitment_update.update_fee.is_none(), true);
4724 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4725 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4726 check_added_monitors!(nodes[0], 1);
4727 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4729 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4730 check_added_monitors!(nodes[1], 1);
4731 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4733 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4734 check_added_monitors!(nodes[1], 1);
4735 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4736 // No commitment_signed so get_event_msg's assert(len == 1) passes
4738 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4739 check_added_monitors!(nodes[0], 1);
4740 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4742 let events = nodes[0].node.get_and_clear_pending_events();
4743 assert_eq!(events.len(), 1);
4745 Event::PendingHTLCsForwardable { .. } => { },
4746 _ => panic!("Unexpected event"),
4748 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4749 nodes[0].node.process_pending_htlc_forwards();
4751 let events = nodes[0].node.get_and_clear_pending_events();
4752 assert_eq!(events.len(), 1);
4754 Event::PaymentReceived { .. } => { },
4755 _ => panic!("Unexpected event"),
4758 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4760 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4761 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4762 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4766 fn test_update_fee() {
4767 let nodes = create_network(2);
4768 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4769 let channel_id = chan.2;
4772 // (1) update_fee/commitment_signed ->
4773 // <- (2) revoke_and_ack
4774 // .- send (3) commitment_signed
4775 // (4) update_fee/commitment_signed ->
4776 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4777 // <- (3) commitment_signed delivered
4778 // send (6) revoke_and_ack -.
4779 // <- (5) deliver revoke_and_ack
4780 // (6) deliver revoke_and_ack ->
4781 // .- send (7) commitment_signed in response to (4)
4782 // <- (7) deliver commitment_signed
4783 // revoke_and_ack ->
4785 // Create and deliver (1)...
4786 let feerate = get_feerate!(nodes[0], channel_id);
4787 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4788 check_added_monitors!(nodes[0], 1);
4790 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4791 assert_eq!(events_0.len(), 1);
4792 let (update_msg, commitment_signed) = match events_0[0] {
4793 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 } } => {
4794 (update_fee.as_ref(), commitment_signed)
4796 _ => panic!("Unexpected event"),
4798 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4800 // Generate (2) and (3):
4801 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4802 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4803 check_added_monitors!(nodes[1], 1);
4806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4808 check_added_monitors!(nodes[0], 1);
4810 // Create and deliver (4)...
4811 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4812 check_added_monitors!(nodes[0], 1);
4813 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4814 assert_eq!(events_0.len(), 1);
4815 let (update_msg, commitment_signed) = match events_0[0] {
4816 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 } } => {
4817 (update_fee.as_ref(), commitment_signed)
4819 _ => panic!("Unexpected event"),
4822 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4823 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4824 check_added_monitors!(nodes[1], 1);
4826 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4827 // No commitment_signed so get_event_msg's assert(len == 1) passes
4829 // Handle (3), creating (6):
4830 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4831 check_added_monitors!(nodes[0], 1);
4832 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4833 // No commitment_signed so get_event_msg's assert(len == 1) passes
4836 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4837 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4838 check_added_monitors!(nodes[0], 1);
4840 // Deliver (6), creating (7):
4841 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4842 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4843 assert!(commitment_update.update_add_htlcs.is_empty());
4844 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4845 assert!(commitment_update.update_fail_htlcs.is_empty());
4846 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4847 assert!(commitment_update.update_fee.is_none());
4848 check_added_monitors!(nodes[1], 1);
4851 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4852 check_added_monitors!(nodes[0], 1);
4853 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4854 // No commitment_signed so get_event_msg's assert(len == 1) passes
4856 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4857 check_added_monitors!(nodes[1], 1);
4858 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4860 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4861 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4862 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4866 fn pre_funding_lock_shutdown_test() {
4867 // Test sending a shutdown prior to funding_locked after funding generation
4868 let nodes = create_network(2);
4869 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4870 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4871 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4872 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4874 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4875 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4876 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4877 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4878 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4880 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4881 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4882 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4883 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4884 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4885 assert!(node_0_none.is_none());
4887 assert!(nodes[0].node.list_channels().is_empty());
4888 assert!(nodes[1].node.list_channels().is_empty());
4892 fn updates_shutdown_wait() {
4893 // Test sending a shutdown with outstanding updates pending
4894 let mut nodes = create_network(3);
4895 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4896 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4897 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4898 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4900 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4902 nodes[0].node.close_channel(&chan_1.2).unwrap();
4903 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4904 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4905 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4906 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4908 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4909 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4911 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4912 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4913 else { panic!("New sends should fail!") };
4914 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4915 else { panic!("New sends should fail!") };
4917 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4918 check_added_monitors!(nodes[2], 1);
4919 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4920 assert!(updates.update_add_htlcs.is_empty());
4921 assert!(updates.update_fail_htlcs.is_empty());
4922 assert!(updates.update_fail_malformed_htlcs.is_empty());
4923 assert!(updates.update_fee.is_none());
4924 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4925 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4926 check_added_monitors!(nodes[1], 1);
4927 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4928 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4930 assert!(updates_2.update_add_htlcs.is_empty());
4931 assert!(updates_2.update_fail_htlcs.is_empty());
4932 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4933 assert!(updates_2.update_fee.is_none());
4934 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4935 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4936 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4938 let events = nodes[0].node.get_and_clear_pending_events();
4939 assert_eq!(events.len(), 1);
4941 Event::PaymentSent { ref payment_preimage } => {
4942 assert_eq!(our_payment_preimage, *payment_preimage);
4944 _ => panic!("Unexpected event"),
4947 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4948 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4949 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4950 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4951 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4952 assert!(node_0_none.is_none());
4954 assert!(nodes[0].node.list_channels().is_empty());
4956 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4957 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4958 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4959 assert!(nodes[1].node.list_channels().is_empty());
4960 assert!(nodes[2].node.list_channels().is_empty());
4964 fn htlc_fail_async_shutdown() {
4965 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4966 let mut nodes = create_network(3);
4967 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4968 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4970 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4971 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4972 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4973 check_added_monitors!(nodes[0], 1);
4974 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4975 assert_eq!(updates.update_add_htlcs.len(), 1);
4976 assert!(updates.update_fulfill_htlcs.is_empty());
4977 assert!(updates.update_fail_htlcs.is_empty());
4978 assert!(updates.update_fail_malformed_htlcs.is_empty());
4979 assert!(updates.update_fee.is_none());
4981 nodes[1].node.close_channel(&chan_1.2).unwrap();
4982 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4983 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4984 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4986 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4987 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4988 check_added_monitors!(nodes[1], 1);
4989 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4990 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4992 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4993 assert!(updates_2.update_add_htlcs.is_empty());
4994 assert!(updates_2.update_fulfill_htlcs.is_empty());
4995 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4996 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4997 assert!(updates_2.update_fee.is_none());
4999 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5000 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5002 let events = nodes[0].node.get_and_clear_pending_events();
5003 assert_eq!(events.len(), 1);
5005 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
5006 assert_eq!(our_payment_hash, *payment_hash);
5007 assert!(!rejected_by_dest);
5009 _ => panic!("Unexpected event"),
5012 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5013 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5014 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5015 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5016 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5017 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5018 assert!(node_0_none.is_none());
5020 assert!(nodes[0].node.list_channels().is_empty());
5022 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5023 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5024 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5025 assert!(nodes[1].node.list_channels().is_empty());
5026 assert!(nodes[2].node.list_channels().is_empty());
5029 fn do_test_shutdown_rebroadcast(recv_count: u8) {
5030 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5031 // messages delivered prior to disconnect
5032 let nodes = create_network(3);
5033 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5034 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5036 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5038 nodes[1].node.close_channel(&chan_1.2).unwrap();
5039 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5041 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5042 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5044 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5048 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5049 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5051 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5052 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5053 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5054 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5056 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5057 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5058 assert!(node_1_shutdown == node_1_2nd_shutdown);
5060 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5061 let node_0_2nd_shutdown = if recv_count > 0 {
5062 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5063 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5066 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5067 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5068 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_2nd_shutdown).unwrap();
5072 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5073 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5075 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5076 check_added_monitors!(nodes[2], 1);
5077 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5078 assert!(updates.update_add_htlcs.is_empty());
5079 assert!(updates.update_fail_htlcs.is_empty());
5080 assert!(updates.update_fail_malformed_htlcs.is_empty());
5081 assert!(updates.update_fee.is_none());
5082 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5083 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5084 check_added_monitors!(nodes[1], 1);
5085 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5086 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5088 assert!(updates_2.update_add_htlcs.is_empty());
5089 assert!(updates_2.update_fail_htlcs.is_empty());
5090 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5091 assert!(updates_2.update_fee.is_none());
5092 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5093 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5094 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5096 let events = nodes[0].node.get_and_clear_pending_events();
5097 assert_eq!(events.len(), 1);
5099 Event::PaymentSent { ref payment_preimage } => {
5100 assert_eq!(our_payment_preimage, *payment_preimage);
5102 _ => panic!("Unexpected event"),
5105 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5107 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5108 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5109 assert!(node_1_closing_signed.is_some());
5112 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5113 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5115 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5116 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5117 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5118 if recv_count == 0 {
5119 // If all closing_signeds weren't delivered we can just resume where we left off...
5120 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5122 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5123 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5124 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5126 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5127 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5128 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5130 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5131 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5133 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5134 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5135 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5137 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5138 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5139 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5140 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5141 assert!(node_0_none.is_none());
5143 // If one node, however, received + responded with an identical closing_signed we end
5144 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5145 // There isn't really anything better we can do simply, but in the future we might
5146 // explore storing a set of recently-closed channels that got disconnected during
5147 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5148 // give our counterparty enough time to (potentially) broadcast a cooperative closing
5150 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5152 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5153 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5154 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5155 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5156 assert_eq!(*channel_id, chan_1.2);
5157 } else { panic!("Needed SendErrorMessage close"); }
5159 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5160 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5161 // closing_signed so we do it ourselves
5162 let events = nodes[0].node.get_and_clear_pending_msg_events();
5163 assert_eq!(events.len(), 1);
5165 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5166 assert_eq!(msg.contents.flags & 2, 2);
5168 _ => panic!("Unexpected event"),
5172 assert!(nodes[0].node.list_channels().is_empty());
5174 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5175 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5176 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5177 assert!(nodes[1].node.list_channels().is_empty());
5178 assert!(nodes[2].node.list_channels().is_empty());
5182 fn test_shutdown_rebroadcast() {
5183 do_test_shutdown_rebroadcast(0);
5184 do_test_shutdown_rebroadcast(1);
5185 do_test_shutdown_rebroadcast(2);
5189 fn fake_network_test() {
5190 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5191 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5192 let nodes = create_network(4);
5194 // Create some initial channels
5195 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5196 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5197 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5199 // Rebalance the network a bit by relaying one payment through all the channels...
5200 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5201 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5202 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5203 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5205 // Send some more payments
5206 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5207 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5208 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5210 // Test failure packets
5211 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5212 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5214 // Add a new channel that skips 3
5215 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5217 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5218 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5219 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5220 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5221 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5222 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5223 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5225 // Do some rebalance loop payments, simultaneously
5226 let mut hops = Vec::with_capacity(3);
5227 hops.push(RouteHop {
5228 pubkey: nodes[2].node.get_our_node_id(),
5229 short_channel_id: chan_2.0.contents.short_channel_id,
5231 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5233 hops.push(RouteHop {
5234 pubkey: nodes[3].node.get_our_node_id(),
5235 short_channel_id: chan_3.0.contents.short_channel_id,
5237 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5239 hops.push(RouteHop {
5240 pubkey: nodes[1].node.get_our_node_id(),
5241 short_channel_id: chan_4.0.contents.short_channel_id,
5243 cltv_expiry_delta: TEST_FINAL_CLTV,
5245 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;
5246 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;
5247 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5249 let mut hops = Vec::with_capacity(3);
5250 hops.push(RouteHop {
5251 pubkey: nodes[3].node.get_our_node_id(),
5252 short_channel_id: chan_4.0.contents.short_channel_id,
5254 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5256 hops.push(RouteHop {
5257 pubkey: nodes[2].node.get_our_node_id(),
5258 short_channel_id: chan_3.0.contents.short_channel_id,
5260 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5262 hops.push(RouteHop {
5263 pubkey: nodes[1].node.get_our_node_id(),
5264 short_channel_id: chan_2.0.contents.short_channel_id,
5266 cltv_expiry_delta: TEST_FINAL_CLTV,
5268 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;
5269 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;
5270 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5272 // Claim the rebalances...
5273 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5274 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5276 // Add a duplicate new channel from 2 to 4
5277 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5279 // Send some payments across both channels
5280 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5281 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5282 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5284 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5286 //TODO: Test that routes work again here as we've been notified that the channel is full
5288 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5289 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5290 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5292 // Close down the channels...
5293 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5294 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5295 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5296 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5297 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5301 fn duplicate_htlc_test() {
5302 // Test that we accept duplicate payment_hash HTLCs across the network and that
5303 // claiming/failing them are all separate and don't effect each other
5304 let mut nodes = create_network(6);
5306 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5307 create_announced_chan_between_nodes(&nodes, 0, 3);
5308 create_announced_chan_between_nodes(&nodes, 1, 3);
5309 create_announced_chan_between_nodes(&nodes, 2, 3);
5310 create_announced_chan_between_nodes(&nodes, 3, 4);
5311 create_announced_chan_between_nodes(&nodes, 3, 5);
5313 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5315 *nodes[0].network_payment_count.borrow_mut() -= 1;
5316 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5318 *nodes[0].network_payment_count.borrow_mut() -= 1;
5319 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5321 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5322 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5323 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5326 #[derive(PartialEq)]
5327 enum HTLCType { NONE, TIMEOUT, SUCCESS }
5328 /// Tests that the given node has broadcast transactions for the given Channel
5330 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5331 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5332 /// broadcast and the revoked outputs were claimed.
5334 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5335 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5337 /// All broadcast transactions must be accounted for in one of the above three types of we'll
5339 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5340 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5341 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5343 let mut res = Vec::with_capacity(2);
5344 node_txn.retain(|tx| {
5345 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5346 check_spends!(tx, chan.3.clone());
5347 if commitment_tx.is_none() {
5348 res.push(tx.clone());
5353 if let Some(explicit_tx) = commitment_tx {
5354 res.push(explicit_tx.clone());
5357 assert_eq!(res.len(), 1);
5359 if has_htlc_tx != HTLCType::NONE {
5360 node_txn.retain(|tx| {
5361 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5362 check_spends!(tx, res[0].clone());
5363 if has_htlc_tx == HTLCType::TIMEOUT {
5364 assert!(tx.lock_time != 0);
5366 assert!(tx.lock_time == 0);
5368 res.push(tx.clone());
5372 assert!(res.len() == 2 || res.len() == 3);
5374 assert_eq!(res[1], res[2]);
5378 assert!(node_txn.is_empty());
5382 /// Tests that the given node has broadcast a claim transaction against the provided revoked
5383 /// HTLC transaction.
5384 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5385 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5386 assert_eq!(node_txn.len(), 1);
5387 node_txn.retain(|tx| {
5388 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5389 check_spends!(tx, revoked_tx.clone());
5393 assert!(node_txn.is_empty());
5396 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5397 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5399 assert!(node_txn.len() >= 1);
5400 assert_eq!(node_txn[0].input.len(), 1);
5401 let mut found_prev = false;
5403 for tx in prev_txn {
5404 if node_txn[0].input[0].previous_output.txid == tx.txid() {
5405 check_spends!(node_txn[0], tx.clone());
5406 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5407 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5413 assert!(found_prev);
5415 let mut res = Vec::new();
5416 mem::swap(&mut *node_txn, &mut res);
5420 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5421 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5422 assert_eq!(events_1.len(), 1);
5423 let as_update = match events_1[0] {
5424 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5427 _ => panic!("Unexpected event"),
5430 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5431 assert_eq!(events_2.len(), 1);
5432 let bs_update = match events_2[0] {
5433 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5436 _ => panic!("Unexpected event"),
5440 node.router.handle_channel_update(&as_update).unwrap();
5441 node.router.handle_channel_update(&bs_update).unwrap();
5445 macro_rules! expect_pending_htlcs_forwardable {
5447 let events = $node.node.get_and_clear_pending_events();
5448 assert_eq!(events.len(), 1);
5450 Event::PendingHTLCsForwardable { .. } => { },
5451 _ => panic!("Unexpected event"),
5453 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5454 $node.node.process_pending_htlc_forwards();
5458 fn do_channel_reserve_test(test_recv: bool) {
5460 use std::sync::atomic::Ordering;
5461 use ln::msgs::HandleError;
5463 macro_rules! get_channel_value_stat {
5464 ($node: expr, $channel_id: expr) => {{
5465 let chan_lock = $node.node.channel_state.lock().unwrap();
5466 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5467 chan.get_value_stat()
5471 let mut nodes = create_network(3);
5472 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5473 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5475 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5476 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5478 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5479 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5481 macro_rules! get_route_and_payment_hash {
5482 ($recv_value: expr) => {{
5483 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5484 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5485 (route, payment_hash, payment_preimage)
5489 macro_rules! expect_forward {
5491 let mut events = $node.node.get_and_clear_pending_msg_events();
5492 assert_eq!(events.len(), 1);
5493 check_added_monitors!($node, 1);
5494 let payment_event = SendEvent::from_event(events.remove(0));
5499 macro_rules! expect_payment_received {
5500 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5501 let events = $node.node.get_and_clear_pending_events();
5502 assert_eq!(events.len(), 1);
5504 Event::PaymentReceived { ref payment_hash, amt } => {
5505 assert_eq!($expected_payment_hash, *payment_hash);
5506 assert_eq!($expected_recv_value, amt);
5508 _ => panic!("Unexpected event"),
5513 let feemsat = 239; // somehow we know?
5514 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5516 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5518 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5520 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5521 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5522 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5524 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5525 _ => panic!("Unknown error variants"),
5529 let mut htlc_id = 0;
5530 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5531 // nodes[0]'s wealth
5533 let amt_msat = recv_value_0 + total_fee_msat;
5534 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5537 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5540 let (stat01_, stat11_, stat12_, stat22_) = (
5541 get_channel_value_stat!(nodes[0], chan_1.2),
5542 get_channel_value_stat!(nodes[1], chan_1.2),
5543 get_channel_value_stat!(nodes[1], chan_2.2),
5544 get_channel_value_stat!(nodes[2], chan_2.2),
5547 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5548 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5549 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5550 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5551 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5555 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5556 // attempt to get channel_reserve violation
5557 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5558 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5560 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5561 _ => panic!("Unknown error variants"),
5565 // adding pending output
5566 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5567 let amt_msat_1 = recv_value_1 + total_fee_msat;
5569 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5570 let payment_event_1 = {
5571 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5572 check_added_monitors!(nodes[0], 1);
5574 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5575 assert_eq!(events.len(), 1);
5576 SendEvent::from_event(events.remove(0))
5578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5580 // channel reserve test with htlc pending output > 0
5581 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5583 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5584 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5585 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5586 _ => panic!("Unknown error variants"),
5591 // test channel_reserve test on nodes[1] side
5592 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5594 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5595 let secp_ctx = Secp256k1::new();
5596 let session_priv = SecretKey::from_slice(&secp_ctx, &{
5597 let mut session_key = [0; 32];
5598 rng::fill_bytes(&mut session_key);
5600 }).expect("RNG is bad!");
5602 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5603 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5604 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5605 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5606 let msg = msgs::UpdateAddHTLC {
5607 channel_id: chan_1.2,
5609 amount_msat: htlc_msat,
5610 payment_hash: our_payment_hash,
5611 cltv_expiry: htlc_cltv,
5612 onion_routing_packet: onion_packet,
5616 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5618 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5620 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5621 assert_eq!(nodes[1].node.list_channels().len(), 1);
5622 assert_eq!(nodes[1].node.list_channels().len(), 1);
5623 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5624 assert_eq!(channel_close_broadcast.len(), 1);
5625 match channel_close_broadcast[0] {
5626 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5627 assert_eq!(msg.contents.flags & 2, 2);
5629 _ => panic!("Unexpected event"),
5635 // split the rest to test holding cell
5636 let recv_value_21 = recv_value_2/2;
5637 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5639 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5640 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);
5643 // now see if they go through on both sides
5644 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5645 // but this will stuck in the holding cell
5646 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5647 check_added_monitors!(nodes[0], 0);
5648 let events = nodes[0].node.get_and_clear_pending_events();
5649 assert_eq!(events.len(), 0);
5651 // test with outbound holding cell amount > 0
5653 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5654 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5655 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5656 _ => panic!("Unknown error variants"),
5660 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5661 // this will also stuck in the holding cell
5662 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5663 check_added_monitors!(nodes[0], 0);
5664 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5665 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5667 // flush the pending htlc
5668 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5669 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5670 check_added_monitors!(nodes[1], 1);
5672 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5673 check_added_monitors!(nodes[0], 1);
5674 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5676 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5677 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5678 // No commitment_signed so get_event_msg's assert(len == 1) passes
5679 check_added_monitors!(nodes[0], 1);
5681 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5682 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5683 check_added_monitors!(nodes[1], 1);
5685 expect_pending_htlcs_forwardable!(nodes[1]);
5687 let ref payment_event_11 = expect_forward!(nodes[1]);
5688 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5689 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5691 expect_pending_htlcs_forwardable!(nodes[2]);
5692 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5694 // flush the htlcs in the holding cell
5695 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5696 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5697 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5698 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5699 expect_pending_htlcs_forwardable!(nodes[1]);
5701 let ref payment_event_3 = expect_forward!(nodes[1]);
5702 assert_eq!(payment_event_3.msgs.len(), 2);
5703 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5704 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5706 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5707 expect_pending_htlcs_forwardable!(nodes[2]);
5709 let events = nodes[2].node.get_and_clear_pending_events();
5710 assert_eq!(events.len(), 2);
5712 Event::PaymentReceived { ref payment_hash, amt } => {
5713 assert_eq!(our_payment_hash_21, *payment_hash);
5714 assert_eq!(recv_value_21, amt);
5716 _ => panic!("Unexpected event"),
5719 Event::PaymentReceived { ref payment_hash, amt } => {
5720 assert_eq!(our_payment_hash_22, *payment_hash);
5721 assert_eq!(recv_value_22, amt);
5723 _ => panic!("Unexpected event"),
5726 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5727 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5728 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5730 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);
5731 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5732 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5733 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5735 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5736 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5740 fn channel_reserve_test() {
5741 do_channel_reserve_test(false);
5742 do_channel_reserve_test(true);
5746 fn channel_monitor_network_test() {
5747 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5748 // tests that ChannelMonitor is able to recover from various states.
5749 let nodes = create_network(5);
5751 // Create some initial channels
5752 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5753 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5754 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5755 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5757 // Rebalance the network a bit by relaying one payment through all the channels...
5758 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5759 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5760 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5761 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5763 // Simple case with no pending HTLCs:
5764 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5766 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5767 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5768 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5769 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5771 get_announce_close_broadcast_events(&nodes, 0, 1);
5772 assert_eq!(nodes[0].node.list_channels().len(), 0);
5773 assert_eq!(nodes[1].node.list_channels().len(), 1);
5775 // One pending HTLC is discarded by the force-close:
5776 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5778 // Simple case of one pending HTLC to HTLC-Timeout
5779 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5781 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5782 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5783 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5784 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5786 get_announce_close_broadcast_events(&nodes, 1, 2);
5787 assert_eq!(nodes[1].node.list_channels().len(), 0);
5788 assert_eq!(nodes[2].node.list_channels().len(), 1);
5790 macro_rules! claim_funds {
5791 ($node: expr, $prev_node: expr, $preimage: expr) => {
5793 assert!($node.node.claim_funds($preimage));
5794 check_added_monitors!($node, 1);
5796 let events = $node.node.get_and_clear_pending_msg_events();
5797 assert_eq!(events.len(), 1);
5799 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5800 assert!(update_add_htlcs.is_empty());
5801 assert!(update_fail_htlcs.is_empty());
5802 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5804 _ => panic!("Unexpected event"),
5810 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5811 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5812 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5814 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5816 // Claim the payment on nodes[3], giving it knowledge of the preimage
5817 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5819 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5820 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5822 check_preimage_claim(&nodes[3], &node_txn);
5824 get_announce_close_broadcast_events(&nodes, 2, 3);
5825 assert_eq!(nodes[2].node.list_channels().len(), 0);
5826 assert_eq!(nodes[3].node.list_channels().len(), 1);
5828 { // Cheat and reset nodes[4]'s height to 1
5829 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5830 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5833 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5834 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5835 // One pending HTLC to time out:
5836 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5837 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5841 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5842 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5843 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5844 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5845 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5848 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5850 // Claim the payment on nodes[4], giving it knowledge of the preimage
5851 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5853 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5854 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5855 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5856 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5857 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5860 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5862 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5863 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5865 check_preimage_claim(&nodes[4], &node_txn);
5867 get_announce_close_broadcast_events(&nodes, 3, 4);
5868 assert_eq!(nodes[3].node.list_channels().len(), 0);
5869 assert_eq!(nodes[4].node.list_channels().len(), 0);
5873 fn test_justice_tx() {
5874 // Test justice txn built on revoked HTLC-Success tx, against both sides
5876 let nodes = create_network(2);
5877 // Create some new channels:
5878 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5880 // A pending HTLC which will be revoked:
5881 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5882 // Get the will-be-revoked local txn from nodes[0]
5883 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5884 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5885 assert_eq!(revoked_local_txn[0].input.len(), 1);
5886 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5887 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5888 assert_eq!(revoked_local_txn[1].input.len(), 1);
5889 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5890 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
5891 // Revoke the old state
5892 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5895 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5896 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5898 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5899 assert_eq!(node_txn.len(), 3);
5900 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5901 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5903 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5904 node_txn.swap_remove(0);
5906 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5908 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5909 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5910 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5911 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5912 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5914 get_announce_close_broadcast_events(&nodes, 0, 1);
5916 assert_eq!(nodes[0].node.list_channels().len(), 0);
5917 assert_eq!(nodes[1].node.list_channels().len(), 0);
5919 // We test justice_tx build by A on B's revoked HTLC-Success tx
5920 // Create some new channels:
5921 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5923 // A pending HTLC which will be revoked:
5924 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5925 // Get the will-be-revoked local txn from B
5926 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5927 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5928 assert_eq!(revoked_local_txn[0].input.len(), 1);
5929 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5930 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5931 // Revoke the old state
5932 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5934 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5935 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5937 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5938 assert_eq!(node_txn.len(), 3);
5939 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5940 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5942 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5943 node_txn.swap_remove(0);
5945 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5947 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5948 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5949 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5950 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5951 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5953 get_announce_close_broadcast_events(&nodes, 0, 1);
5954 assert_eq!(nodes[0].node.list_channels().len(), 0);
5955 assert_eq!(nodes[1].node.list_channels().len(), 0);
5959 fn revoked_output_claim() {
5960 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5961 // transaction is broadcast by its counterparty
5962 let nodes = create_network(2);
5963 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5964 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5965 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5966 assert_eq!(revoked_local_txn.len(), 1);
5967 // Only output is the full channel value back to nodes[0]:
5968 assert_eq!(revoked_local_txn[0].output.len(), 1);
5969 // Send a payment through, updating everyone's latest commitment txn
5970 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5972 // Inform nodes[1] that nodes[0] broadcast a stale tx
5973 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5974 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5975 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5976 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5978 assert_eq!(node_txn[0], node_txn[2]);
5980 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5981 check_spends!(node_txn[1], chan_1.3.clone());
5983 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5984 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5985 get_announce_close_broadcast_events(&nodes, 0, 1);
5989 fn claim_htlc_outputs_shared_tx() {
5990 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5991 let nodes = create_network(2);
5993 // Create some new channel:
5994 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5996 // Rebalance the network to generate htlc in the two directions
5997 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5998 // 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
5999 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6000 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6002 // Get the will-be-revoked local txn from node[0]
6003 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6004 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6005 assert_eq!(revoked_local_txn[0].input.len(), 1);
6006 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6007 assert_eq!(revoked_local_txn[1].input.len(), 1);
6008 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6009 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
6010 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6012 //Revoke the old state
6013 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6016 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6017 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6018 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6020 let events = nodes[1].node.get_and_clear_pending_events();
6021 assert_eq!(events.len(), 1);
6023 Event::PaymentFailed { payment_hash, .. } => {
6024 assert_eq!(payment_hash, payment_hash_2);
6026 _ => panic!("Unexpected event"),
6029 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6030 assert_eq!(node_txn.len(), 4);
6032 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6033 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6035 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6037 let mut witness_lens = BTreeSet::new();
6038 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6039 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6040 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6041 assert_eq!(witness_lens.len(), 3);
6042 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6043 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
6044 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
6046 // Next nodes[1] broadcasts its current local tx state:
6047 assert_eq!(node_txn[1].input.len(), 1);
6048 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6050 assert_eq!(node_txn[2].input.len(), 1);
6051 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6052 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
6053 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6054 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6055 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6057 get_announce_close_broadcast_events(&nodes, 0, 1);
6058 assert_eq!(nodes[0].node.list_channels().len(), 0);
6059 assert_eq!(nodes[1].node.list_channels().len(), 0);
6063 fn claim_htlc_outputs_single_tx() {
6064 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6065 let nodes = create_network(2);
6067 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6069 // Rebalance the network to generate htlc in the two directions
6070 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6071 // 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
6072 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6073 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6074 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6076 // Get the will-be-revoked local txn from node[0]
6077 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6079 //Revoke the old state
6080 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6083 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6084 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6085 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6087 let events = nodes[1].node.get_and_clear_pending_events();
6088 assert_eq!(events.len(), 1);
6090 Event::PaymentFailed { payment_hash, .. } => {
6091 assert_eq!(payment_hash, payment_hash_2);
6093 _ => panic!("Unexpected event"),
6096 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6097 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)
6099 assert_eq!(node_txn[0], node_txn[7]);
6100 assert_eq!(node_txn[1], node_txn[8]);
6101 assert_eq!(node_txn[2], node_txn[9]);
6102 assert_eq!(node_txn[3], node_txn[10]);
6103 assert_eq!(node_txn[4], node_txn[11]);
6104 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6105 assert_eq!(node_txn[4], node_txn[6]);
6107 assert_eq!(node_txn[0].input.len(), 1);
6108 assert_eq!(node_txn[1].input.len(), 1);
6109 assert_eq!(node_txn[2].input.len(), 1);
6111 let mut revoked_tx_map = HashMap::new();
6112 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6113 node_txn[0].verify(&revoked_tx_map).unwrap();
6114 node_txn[1].verify(&revoked_tx_map).unwrap();
6115 node_txn[2].verify(&revoked_tx_map).unwrap();
6117 let mut witness_lens = BTreeSet::new();
6118 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6119 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6120 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6121 assert_eq!(witness_lens.len(), 3);
6122 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6123 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
6124 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
6126 assert_eq!(node_txn[3].input.len(), 1);
6127 check_spends!(node_txn[3], chan_1.3.clone());
6129 assert_eq!(node_txn[4].input.len(), 1);
6130 let witness_script = node_txn[4].input[0].witness.last().unwrap();
6131 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
6132 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6133 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6134 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6136 get_announce_close_broadcast_events(&nodes, 0, 1);
6137 assert_eq!(nodes[0].node.list_channels().len(), 0);
6138 assert_eq!(nodes[1].node.list_channels().len(), 0);
6142 fn test_htlc_ignore_latest_remote_commitment() {
6143 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6144 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6145 let nodes = create_network(2);
6146 create_announced_chan_between_nodes(&nodes, 0, 1);
6148 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6149 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6151 let events = nodes[0].node.get_and_clear_pending_msg_events();
6152 assert_eq!(events.len(), 1);
6154 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6155 assert_eq!(flags & 0b10, 0b10);
6157 _ => panic!("Unexpected event"),
6161 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6162 assert_eq!(node_txn.len(), 2);
6164 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6165 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6168 let events = nodes[1].node.get_and_clear_pending_msg_events();
6169 assert_eq!(events.len(), 1);
6171 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6172 assert_eq!(flags & 0b10, 0b10);
6174 _ => panic!("Unexpected event"),
6178 // Duplicate the block_connected call since this may happen due to other listeners
6179 // registering new transactions
6180 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6184 fn test_force_close_fail_back() {
6185 // Check which HTLCs are failed-backwards on channel force-closure
6186 let mut nodes = create_network(3);
6187 create_announced_chan_between_nodes(&nodes, 0, 1);
6188 create_announced_chan_between_nodes(&nodes, 1, 2);
6190 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6192 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6194 let mut payment_event = {
6195 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6196 check_added_monitors!(nodes[0], 1);
6198 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6199 assert_eq!(events.len(), 1);
6200 SendEvent::from_event(events.remove(0))
6203 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6204 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6206 let events_1 = nodes[1].node.get_and_clear_pending_events();
6207 assert_eq!(events_1.len(), 1);
6209 Event::PendingHTLCsForwardable { .. } => { },
6210 _ => panic!("Unexpected event"),
6213 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6214 nodes[1].node.process_pending_htlc_forwards();
6216 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6217 assert_eq!(events_2.len(), 1);
6218 payment_event = SendEvent::from_event(events_2.remove(0));
6219 assert_eq!(payment_event.msgs.len(), 1);
6221 check_added_monitors!(nodes[1], 1);
6222 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6223 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6224 check_added_monitors!(nodes[2], 1);
6225 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6227 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6228 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6229 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6231 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6232 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6233 assert_eq!(events_3.len(), 1);
6235 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6236 assert_eq!(flags & 0b10, 0b10);
6238 _ => panic!("Unexpected event"),
6242 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6243 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6244 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6245 // back to nodes[1] upon timeout otherwise.
6246 assert_eq!(node_txn.len(), 1);
6250 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6251 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6253 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6254 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6255 assert_eq!(events_4.len(), 1);
6257 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6258 assert_eq!(flags & 0b10, 0b10);
6260 _ => panic!("Unexpected event"),
6263 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6265 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6266 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6267 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6269 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6270 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6271 assert_eq!(node_txn.len(), 1);
6272 assert_eq!(node_txn[0].input.len(), 1);
6273 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6274 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6275 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6277 check_spends!(node_txn[0], tx);
6281 fn test_unconf_chan() {
6282 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6283 let nodes = create_network(2);
6284 create_announced_chan_between_nodes(&nodes, 0, 1);
6286 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6287 assert_eq!(channel_state.by_id.len(), 1);
6288 assert_eq!(channel_state.short_to_id.len(), 1);
6289 mem::drop(channel_state);
6291 let mut headers = Vec::new();
6292 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6293 headers.push(header.clone());
6295 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6296 headers.push(header.clone());
6298 while !headers.is_empty() {
6299 nodes[0].node.block_disconnected(&headers.pop().unwrap());
6302 let events = nodes[0].node.get_and_clear_pending_msg_events();
6303 assert_eq!(events.len(), 1);
6305 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6306 assert_eq!(flags & 0b10, 0b10);
6308 _ => panic!("Unexpected event"),
6311 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6312 assert_eq!(channel_state.by_id.len(), 0);
6313 assert_eq!(channel_state.short_to_id.len(), 0);
6316 macro_rules! get_chan_reestablish_msgs {
6317 ($src_node: expr, $dst_node: expr) => {
6319 let mut res = Vec::with_capacity(1);
6320 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6321 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6322 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6323 res.push(msg.clone());
6325 panic!("Unexpected event")
6333 macro_rules! handle_chan_reestablish_msgs {
6334 ($src_node: expr, $dst_node: expr) => {
6336 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6338 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6340 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6346 let mut revoke_and_ack = None;
6347 let mut commitment_update = None;
6348 let order = if let Some(ev) = msg_events.get(idx) {
6351 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6352 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6353 revoke_and_ack = Some(msg.clone());
6354 RAACommitmentOrder::RevokeAndACKFirst
6356 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6357 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6358 commitment_update = Some(updates.clone());
6359 RAACommitmentOrder::CommitmentFirst
6361 _ => panic!("Unexpected event"),
6364 RAACommitmentOrder::CommitmentFirst
6367 if let Some(ev) = msg_events.get(idx) {
6369 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6370 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6371 assert!(revoke_and_ack.is_none());
6372 revoke_and_ack = Some(msg.clone());
6374 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6375 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6376 assert!(commitment_update.is_none());
6377 commitment_update = Some(updates.clone());
6379 _ => panic!("Unexpected event"),
6383 (funding_locked, revoke_and_ack, commitment_update, order)
6388 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6389 /// for claims/fails they are separated out.
6390 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)) {
6391 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6392 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6393 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6394 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6396 if send_funding_locked.0 {
6397 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6399 for reestablish in reestablish_1.iter() {
6400 assert_eq!(reestablish.next_remote_commitment_number, 0);
6403 if send_funding_locked.1 {
6404 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6406 for reestablish in reestablish_2.iter() {
6407 assert_eq!(reestablish.next_remote_commitment_number, 0);
6410 if send_funding_locked.0 || send_funding_locked.1 {
6411 // If we expect any funding_locked's, both sides better have set
6412 // next_local_commitment_number to 1
6413 for reestablish in reestablish_1.iter() {
6414 assert_eq!(reestablish.next_local_commitment_number, 1);
6416 for reestablish in reestablish_2.iter() {
6417 assert_eq!(reestablish.next_local_commitment_number, 1);
6421 let mut resp_1 = Vec::new();
6422 for msg in reestablish_1 {
6423 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6424 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6426 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6427 check_added_monitors!(node_b, 1);
6429 check_added_monitors!(node_b, 0);
6432 let mut resp_2 = Vec::new();
6433 for msg in reestablish_2 {
6434 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6435 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6437 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6438 check_added_monitors!(node_a, 1);
6440 check_added_monitors!(node_a, 0);
6443 // We dont yet support both needing updates, as that would require a different commitment dance:
6444 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
6445 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
6447 for chan_msgs in resp_1.drain(..) {
6448 if send_funding_locked.0 {
6449 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6450 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
6451 if !announcement_event.is_empty() {
6452 assert_eq!(announcement_event.len(), 1);
6453 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6454 //TODO: Test announcement_sigs re-sending
6455 } else { panic!("Unexpected event!"); }
6458 assert!(chan_msgs.0.is_none());
6461 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6462 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6463 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6464 check_added_monitors!(node_a, 1);
6466 assert!(chan_msgs.1.is_none());
6468 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6469 let commitment_update = chan_msgs.2.unwrap();
6470 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6471 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
6473 assert!(commitment_update.update_add_htlcs.is_empty());
6475 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6476 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6477 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6478 for update_add in commitment_update.update_add_htlcs {
6479 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
6481 for update_fulfill in commitment_update.update_fulfill_htlcs {
6482 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
6484 for update_fail in commitment_update.update_fail_htlcs {
6485 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
6488 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6489 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
6491 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6492 check_added_monitors!(node_a, 1);
6493 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
6494 // No commitment_signed so get_event_msg's assert(len == 1) passes
6495 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6496 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6497 check_added_monitors!(node_b, 1);
6500 assert!(chan_msgs.2.is_none());
6504 for chan_msgs in resp_2.drain(..) {
6505 if send_funding_locked.1 {
6506 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6507 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
6508 if !announcement_event.is_empty() {
6509 assert_eq!(announcement_event.len(), 1);
6510 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6511 //TODO: Test announcement_sigs re-sending
6512 } else { panic!("Unexpected event!"); }
6515 assert!(chan_msgs.0.is_none());
6518 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6519 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6520 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6521 check_added_monitors!(node_b, 1);
6523 assert!(chan_msgs.1.is_none());
6525 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6526 let commitment_update = chan_msgs.2.unwrap();
6527 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6528 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
6530 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6531 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6532 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6533 for update_add in commitment_update.update_add_htlcs {
6534 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
6536 for update_fulfill in commitment_update.update_fulfill_htlcs {
6537 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
6539 for update_fail in commitment_update.update_fail_htlcs {
6540 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
6543 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6544 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
6546 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6547 check_added_monitors!(node_b, 1);
6548 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
6549 // No commitment_signed so get_event_msg's assert(len == 1) passes
6550 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6551 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6552 check_added_monitors!(node_a, 1);
6555 assert!(chan_msgs.2.is_none());
6561 fn test_simple_peer_disconnect() {
6562 // Test that we can reconnect when there are no lost messages
6563 let nodes = create_network(3);
6564 create_announced_chan_between_nodes(&nodes, 0, 1);
6565 create_announced_chan_between_nodes(&nodes, 1, 2);
6567 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6568 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6569 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6571 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6572 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6573 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
6574 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
6576 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6577 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6578 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6580 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6581 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6582 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6583 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6585 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6586 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6588 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
6589 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
6591 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
6593 let events = nodes[0].node.get_and_clear_pending_events();
6594 assert_eq!(events.len(), 2);
6596 Event::PaymentSent { payment_preimage } => {
6597 assert_eq!(payment_preimage, payment_preimage_3);
6599 _ => panic!("Unexpected event"),
6602 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
6603 assert_eq!(payment_hash, payment_hash_5);
6604 assert!(rejected_by_dest);
6606 _ => panic!("Unexpected event"),
6610 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
6611 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
6614 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
6615 // Test that we can reconnect when in-flight HTLC updates get dropped
6616 let mut nodes = create_network(2);
6617 if messages_delivered == 0 {
6618 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
6619 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
6621 create_announced_chan_between_nodes(&nodes, 0, 1);
6624 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();
6625 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6627 let payment_event = {
6628 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
6629 check_added_monitors!(nodes[0], 1);
6631 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6632 assert_eq!(events.len(), 1);
6633 SendEvent::from_event(events.remove(0))
6635 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
6637 if messages_delivered < 2 {
6638 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
6640 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6641 if messages_delivered >= 3 {
6642 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6643 check_added_monitors!(nodes[1], 1);
6644 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6646 if messages_delivered >= 4 {
6647 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6648 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6649 check_added_monitors!(nodes[0], 1);
6651 if messages_delivered >= 5 {
6652 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
6653 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6654 // No commitment_signed so get_event_msg's assert(len == 1) passes
6655 check_added_monitors!(nodes[0], 1);
6657 if messages_delivered >= 6 {
6658 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6659 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6660 check_added_monitors!(nodes[1], 1);
6667 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6668 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6669 if messages_delivered < 3 {
6670 // Even if the funding_locked messages get exchanged, as long as nothing further was
6671 // received on either side, both sides will need to resend them.
6672 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
6673 } else if messages_delivered == 3 {
6674 // nodes[0] still wants its RAA + commitment_signed
6675 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
6676 } else if messages_delivered == 4 {
6677 // nodes[0] still wants its commitment_signed
6678 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
6679 } else if messages_delivered == 5 {
6680 // nodes[1] still wants its final RAA
6681 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
6682 } else if messages_delivered == 6 {
6683 // Everything was delivered...
6684 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6687 let events_1 = nodes[1].node.get_and_clear_pending_events();
6688 assert_eq!(events_1.len(), 1);
6690 Event::PendingHTLCsForwardable { .. } => { },
6691 _ => panic!("Unexpected event"),
6694 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6695 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6696 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6698 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6699 nodes[1].node.process_pending_htlc_forwards();
6701 let events_2 = nodes[1].node.get_and_clear_pending_events();
6702 assert_eq!(events_2.len(), 1);
6704 Event::PaymentReceived { ref payment_hash, amt } => {
6705 assert_eq!(payment_hash_1, *payment_hash);
6706 assert_eq!(amt, 1000000);
6708 _ => panic!("Unexpected event"),
6711 nodes[1].node.claim_funds(payment_preimage_1);
6712 check_added_monitors!(nodes[1], 1);
6714 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
6715 assert_eq!(events_3.len(), 1);
6716 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
6717 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6718 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6719 assert!(updates.update_add_htlcs.is_empty());
6720 assert!(updates.update_fail_htlcs.is_empty());
6721 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6722 assert!(updates.update_fail_malformed_htlcs.is_empty());
6723 assert!(updates.update_fee.is_none());
6724 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
6726 _ => panic!("Unexpected event"),
6729 if messages_delivered >= 1 {
6730 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
6732 let events_4 = nodes[0].node.get_and_clear_pending_events();
6733 assert_eq!(events_4.len(), 1);
6735 Event::PaymentSent { ref payment_preimage } => {
6736 assert_eq!(payment_preimage_1, *payment_preimage);
6738 _ => panic!("Unexpected event"),
6741 if messages_delivered >= 2 {
6742 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
6743 check_added_monitors!(nodes[0], 1);
6744 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6746 if messages_delivered >= 3 {
6747 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6748 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6749 check_added_monitors!(nodes[1], 1);
6751 if messages_delivered >= 4 {
6752 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6753 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6754 // No commitment_signed so get_event_msg's assert(len == 1) passes
6755 check_added_monitors!(nodes[1], 1);
6757 if messages_delivered >= 5 {
6758 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6759 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6760 check_added_monitors!(nodes[0], 1);
6767 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6768 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6769 if messages_delivered < 2 {
6770 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
6771 //TODO: Deduplicate PaymentSent events, then enable this if:
6772 //if messages_delivered < 1 {
6773 let events_4 = nodes[0].node.get_and_clear_pending_events();
6774 assert_eq!(events_4.len(), 1);
6776 Event::PaymentSent { ref payment_preimage } => {
6777 assert_eq!(payment_preimage_1, *payment_preimage);
6779 _ => panic!("Unexpected event"),
6782 } else if messages_delivered == 2 {
6783 // nodes[0] still wants its RAA + commitment_signed
6784 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
6785 } else if messages_delivered == 3 {
6786 // nodes[0] still wants its commitment_signed
6787 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
6788 } else if messages_delivered == 4 {
6789 // nodes[1] still wants its final RAA
6790 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
6791 } else if messages_delivered == 5 {
6792 // Everything was delivered...
6793 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6796 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6797 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6798 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6800 // Channel should still work fine...
6801 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
6802 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
6806 fn test_drop_messages_peer_disconnect_a() {
6807 do_test_drop_messages_peer_disconnect(0);
6808 do_test_drop_messages_peer_disconnect(1);
6809 do_test_drop_messages_peer_disconnect(2);
6810 do_test_drop_messages_peer_disconnect(3);
6814 fn test_drop_messages_peer_disconnect_b() {
6815 do_test_drop_messages_peer_disconnect(4);
6816 do_test_drop_messages_peer_disconnect(5);
6817 do_test_drop_messages_peer_disconnect(6);
6821 fn test_funding_peer_disconnect() {
6822 // Test that we can lock in our funding tx while disconnected
6823 let nodes = create_network(2);
6824 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
6826 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6827 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6829 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
6830 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
6831 assert_eq!(events_1.len(), 1);
6833 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
6834 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6836 _ => panic!("Unexpected event"),
6839 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6841 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6842 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6844 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
6845 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6846 assert_eq!(events_2.len(), 2);
6848 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
6849 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6851 _ => panic!("Unexpected event"),
6854 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
6855 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6857 _ => panic!("Unexpected event"),
6860 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6862 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
6863 // rebroadcasting announcement_signatures upon reconnect.
6865 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();
6866 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
6867 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
6871 fn test_drop_messages_peer_disconnect_dual_htlc() {
6872 // Test that we can handle reconnecting when both sides of a channel have pending
6873 // commitment_updates when we disconnect.
6874 let mut nodes = create_network(2);
6875 create_announced_chan_between_nodes(&nodes, 0, 1);
6877 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6879 // Now try to send a second payment which will fail to send
6880 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6881 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6883 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
6884 check_added_monitors!(nodes[0], 1);
6886 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
6887 assert_eq!(events_1.len(), 1);
6889 MessageSendEvent::UpdateHTLCs { .. } => {},
6890 _ => panic!("Unexpected event"),
6893 assert!(nodes[1].node.claim_funds(payment_preimage_1));
6894 check_added_monitors!(nodes[1], 1);
6896 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6897 assert_eq!(events_2.len(), 1);
6899 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 } } => {
6900 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6901 assert!(update_add_htlcs.is_empty());
6902 assert_eq!(update_fulfill_htlcs.len(), 1);
6903 assert!(update_fail_htlcs.is_empty());
6904 assert!(update_fail_malformed_htlcs.is_empty());
6905 assert!(update_fee.is_none());
6907 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
6908 let events_3 = nodes[0].node.get_and_clear_pending_events();
6909 assert_eq!(events_3.len(), 1);
6911 Event::PaymentSent { ref payment_preimage } => {
6912 assert_eq!(*payment_preimage, payment_preimage_1);
6914 _ => panic!("Unexpected event"),
6917 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6918 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6919 // No commitment_signed so get_event_msg's assert(len == 1) passes
6920 check_added_monitors!(nodes[0], 1);
6922 _ => panic!("Unexpected event"),
6925 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6926 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6928 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6929 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6930 assert_eq!(reestablish_1.len(), 1);
6931 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6932 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6933 assert_eq!(reestablish_2.len(), 1);
6935 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
6936 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6937 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
6938 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6940 assert!(as_resp.0.is_none());
6941 assert!(bs_resp.0.is_none());
6943 assert!(bs_resp.1.is_none());
6944 assert!(bs_resp.2.is_none());
6946 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
6948 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
6949 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
6950 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
6951 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
6952 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
6953 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();
6954 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
6955 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6956 // No commitment_signed so get_event_msg's assert(len == 1) passes
6957 check_added_monitors!(nodes[1], 1);
6959 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
6960 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6961 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
6962 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
6963 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
6964 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
6965 assert!(bs_second_commitment_signed.update_fee.is_none());
6966 check_added_monitors!(nodes[1], 1);
6968 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6969 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6970 assert!(as_commitment_signed.update_add_htlcs.is_empty());
6971 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
6972 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
6973 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
6974 assert!(as_commitment_signed.update_fee.is_none());
6975 check_added_monitors!(nodes[0], 1);
6977 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
6978 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6979 // No commitment_signed so get_event_msg's assert(len == 1) passes
6980 check_added_monitors!(nodes[0], 1);
6982 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
6983 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6984 // No commitment_signed so get_event_msg's assert(len == 1) passes
6985 check_added_monitors!(nodes[1], 1);
6987 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6988 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6989 check_added_monitors!(nodes[1], 1);
6991 let events_4 = nodes[1].node.get_and_clear_pending_events();
6992 assert_eq!(events_4.len(), 1);
6994 Event::PendingHTLCsForwardable { .. } => { },
6995 _ => panic!("Unexpected event"),
6998 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6999 nodes[1].node.process_pending_htlc_forwards();
7001 let events_5 = nodes[1].node.get_and_clear_pending_events();
7002 assert_eq!(events_5.len(), 1);
7004 Event::PaymentReceived { ref payment_hash, amt: _ } => {
7005 assert_eq!(payment_hash_2, *payment_hash);
7007 _ => panic!("Unexpected event"),
7010 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7011 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7012 check_added_monitors!(nodes[0], 1);
7014 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7018 fn test_simple_monitor_permanent_update_fail() {
7019 // Test that we handle a simple permanent monitor update failure
7020 let mut nodes = create_network(2);
7021 create_announced_chan_between_nodes(&nodes, 0, 1);
7023 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7024 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7026 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7027 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7028 check_added_monitors!(nodes[0], 1);
7030 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7031 assert_eq!(events_1.len(), 2);
7033 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7034 _ => panic!("Unexpected event"),
7037 MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7038 _ => panic!("Unexpected event"),
7041 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7042 // PaymentFailed event
7044 assert_eq!(nodes[0].node.list_channels().len(), 0);
7047 fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7048 // Test that we can recover from a simple temporary monitor update failure optionally with
7049 // a disconnect in between
7050 let mut nodes = create_network(2);
7051 create_announced_chan_between_nodes(&nodes, 0, 1);
7053 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7054 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7056 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7057 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7058 check_added_monitors!(nodes[0], 1);
7060 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7061 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7062 assert_eq!(nodes[0].node.list_channels().len(), 1);
7065 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7066 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7067 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7070 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7071 nodes[0].node.test_restore_channel_monitor();
7072 check_added_monitors!(nodes[0], 1);
7074 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7075 assert_eq!(events_2.len(), 1);
7076 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7077 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7078 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7079 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7081 expect_pending_htlcs_forwardable!(nodes[1]);
7083 let events_3 = nodes[1].node.get_and_clear_pending_events();
7084 assert_eq!(events_3.len(), 1);
7086 Event::PaymentReceived { ref payment_hash, amt } => {
7087 assert_eq!(payment_hash_1, *payment_hash);
7088 assert_eq!(amt, 1000000);
7090 _ => panic!("Unexpected event"),
7093 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7095 // Now set it to failed again...
7096 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7097 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7098 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7099 check_added_monitors!(nodes[0], 1);
7101 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7102 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7103 assert_eq!(nodes[0].node.list_channels().len(), 1);
7106 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7107 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7108 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7111 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7112 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7113 nodes[0].node.test_restore_channel_monitor();
7114 check_added_monitors!(nodes[0], 1);
7116 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7117 assert_eq!(events_5.len(), 1);
7119 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7120 _ => panic!("Unexpected event"),
7123 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7124 // PaymentFailed event
7126 assert_eq!(nodes[0].node.list_channels().len(), 0);
7130 fn test_simple_monitor_temporary_update_fail() {
7131 do_test_simple_monitor_temporary_update_fail(false);
7132 do_test_simple_monitor_temporary_update_fail(true);
7135 fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7136 let disconnect_flags = 8 | 16;
7138 // Test that we can recover from a temporary monitor update failure with some in-flight
7139 // HTLCs going on at the same time potentially with some disconnection thrown in.
7140 // * First we route a payment, then get a temporary monitor update failure when trying to
7141 // route a second payment. We then claim the first payment.
7142 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7143 // TemporaryFailure likely indicates net disconnect which resulted in failing to update
7144 // the ChannelMonitor on a watchtower).
7145 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7146 // immediately, otherwise we wait sconnect and deliver them via the reconnect
7147 // channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7148 // disconnect_count & !disconnect_flags is 0).
7149 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7150 // through message sending, potentially disconnect/reconnecting multiple times based on
7151 // disconnect_count, to get the update_fulfill_htlc through.
7152 // * We then walk through more message exchanges to get the original update_add_htlc
7153 // through, swapping message ordering based on disconnect_count & 8 and optionally
7154 // disconnect/reconnecting based on disconnect_count.
7155 let mut nodes = create_network(2);
7156 create_announced_chan_between_nodes(&nodes, 0, 1);
7158 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7160 // Now try to send a second payment which will fail to send
7161 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7162 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7164 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7165 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7166 check_added_monitors!(nodes[0], 1);
7168 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7169 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7170 assert_eq!(nodes[0].node.list_channels().len(), 1);
7172 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7173 // but nodes[0] won't respond since it is frozen.
7174 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7175 check_added_monitors!(nodes[1], 1);
7176 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7177 assert_eq!(events_2.len(), 1);
7178 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7179 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 } } => {
7180 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7181 assert!(update_add_htlcs.is_empty());
7182 assert_eq!(update_fulfill_htlcs.len(), 1);
7183 assert!(update_fail_htlcs.is_empty());
7184 assert!(update_fail_malformed_htlcs.is_empty());
7185 assert!(update_fee.is_none());
7187 if (disconnect_count & 16) == 0 {
7188 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7189 let events_3 = nodes[0].node.get_and_clear_pending_events();
7190 assert_eq!(events_3.len(), 1);
7192 Event::PaymentSent { ref payment_preimage } => {
7193 assert_eq!(*payment_preimage, payment_preimage_1);
7195 _ => panic!("Unexpected event"),
7198 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) {
7199 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7200 } else { panic!(); }
7203 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7205 _ => panic!("Unexpected event"),
7208 if disconnect_count & !disconnect_flags > 0 {
7209 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7210 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7213 // Now fix monitor updating...
7214 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7215 nodes[0].node.test_restore_channel_monitor();
7216 check_added_monitors!(nodes[0], 1);
7218 macro_rules! disconnect_reconnect_peers { () => { {
7219 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7220 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7222 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7223 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7224 assert_eq!(reestablish_1.len(), 1);
7225 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7226 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7227 assert_eq!(reestablish_2.len(), 1);
7229 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7230 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7231 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7232 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7234 assert!(as_resp.0.is_none());
7235 assert!(bs_resp.0.is_none());
7237 (reestablish_1, reestablish_2, as_resp, bs_resp)
7240 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7241 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7242 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7244 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7245 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7246 assert_eq!(reestablish_1.len(), 1);
7247 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7248 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7249 assert_eq!(reestablish_2.len(), 1);
7251 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7252 check_added_monitors!(nodes[0], 0);
7253 let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7254 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7255 check_added_monitors!(nodes[1], 0);
7256 let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7258 assert!(as_resp.0.is_none());
7259 assert!(bs_resp.0.is_none());
7261 assert!(bs_resp.1.is_none());
7262 if (disconnect_count & 16) == 0 {
7263 assert!(bs_resp.2.is_none());
7265 assert!(as_resp.1.is_some());
7266 assert!(as_resp.2.is_some());
7267 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7269 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7270 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7271 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7272 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7273 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7274 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7276 assert!(as_resp.1.is_none());
7278 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();
7279 let events_3 = nodes[0].node.get_and_clear_pending_events();
7280 assert_eq!(events_3.len(), 1);
7282 Event::PaymentSent { ref payment_preimage } => {
7283 assert_eq!(*payment_preimage, payment_preimage_1);
7285 _ => panic!("Unexpected event"),
7288 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7289 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7290 // No commitment_signed so get_event_msg's assert(len == 1) passes
7291 check_added_monitors!(nodes[0], 1);
7293 as_resp.1 = Some(as_resp_raa);
7297 if disconnect_count & !disconnect_flags > 1 {
7298 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7300 if (disconnect_count & 16) == 0 {
7301 assert!(reestablish_1 == second_reestablish_1);
7302 assert!(reestablish_2 == second_reestablish_2);
7304 assert!(as_resp == second_as_resp);
7305 assert!(bs_resp == second_bs_resp);
7308 (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7310 let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7311 assert_eq!(events_4.len(), 2);
7312 (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7313 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7314 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7317 _ => panic!("Unexpected event"),
7321 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7323 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7324 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7325 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7326 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7327 check_added_monitors!(nodes[1], 1);
7329 if disconnect_count & !disconnect_flags > 2 {
7330 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7332 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7333 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7335 assert!(as_resp.2.is_none());
7336 assert!(bs_resp.2.is_none());
7339 let as_commitment_update;
7340 let bs_second_commitment_update;
7342 macro_rules! handle_bs_raa { () => {
7343 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7344 as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7345 assert!(as_commitment_update.update_add_htlcs.is_empty());
7346 assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7347 assert!(as_commitment_update.update_fail_htlcs.is_empty());
7348 assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7349 assert!(as_commitment_update.update_fee.is_none());
7350 check_added_monitors!(nodes[0], 1);
7353 macro_rules! handle_initial_raa { () => {
7354 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7355 bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7356 assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7357 assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7358 assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7359 assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7360 assert!(bs_second_commitment_update.update_fee.is_none());
7361 check_added_monitors!(nodes[1], 1);
7364 if (disconnect_count & 8) == 0 {
7367 if disconnect_count & !disconnect_flags > 3 {
7368 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7370 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7371 assert!(bs_resp.1.is_none());
7373 assert!(as_resp.2.unwrap() == as_commitment_update);
7374 assert!(bs_resp.2.is_none());
7376 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7379 handle_initial_raa!();
7381 if disconnect_count & !disconnect_flags > 4 {
7382 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7384 assert!(as_resp.1.is_none());
7385 assert!(bs_resp.1.is_none());
7387 assert!(as_resp.2.unwrap() == as_commitment_update);
7388 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7391 handle_initial_raa!();
7393 if disconnect_count & !disconnect_flags > 3 {
7394 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7396 assert!(as_resp.1.is_none());
7397 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7399 assert!(as_resp.2.is_none());
7400 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7402 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7407 if disconnect_count & !disconnect_flags > 4 {
7408 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7410 assert!(as_resp.1.is_none());
7411 assert!(bs_resp.1.is_none());
7413 assert!(as_resp.2.unwrap() == as_commitment_update);
7414 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7418 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7419 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7420 // No commitment_signed so get_event_msg's assert(len == 1) passes
7421 check_added_monitors!(nodes[0], 1);
7423 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7424 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7425 // No commitment_signed so get_event_msg's assert(len == 1) passes
7426 check_added_monitors!(nodes[1], 1);
7428 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7429 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7430 check_added_monitors!(nodes[1], 1);
7432 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7433 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7434 check_added_monitors!(nodes[0], 1);
7436 expect_pending_htlcs_forwardable!(nodes[1]);
7438 let events_5 = nodes[1].node.get_and_clear_pending_events();
7439 assert_eq!(events_5.len(), 1);
7441 Event::PaymentReceived { ref payment_hash, amt } => {
7442 assert_eq!(payment_hash_2, *payment_hash);
7443 assert_eq!(amt, 1000000);
7445 _ => panic!("Unexpected event"),
7448 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7452 fn test_monitor_temporary_update_fail_a() {
7453 do_test_monitor_temporary_update_fail(0);
7454 do_test_monitor_temporary_update_fail(1);
7455 do_test_monitor_temporary_update_fail(2);
7456 do_test_monitor_temporary_update_fail(3);
7457 do_test_monitor_temporary_update_fail(4);
7458 do_test_monitor_temporary_update_fail(5);
7462 fn test_monitor_temporary_update_fail_b() {
7463 do_test_monitor_temporary_update_fail(2 | 8);
7464 do_test_monitor_temporary_update_fail(3 | 8);
7465 do_test_monitor_temporary_update_fail(4 | 8);
7466 do_test_monitor_temporary_update_fail(5 | 8);
7470 fn test_monitor_temporary_update_fail_c() {
7471 do_test_monitor_temporary_update_fail(1 | 16);
7472 do_test_monitor_temporary_update_fail(2 | 16);
7473 do_test_monitor_temporary_update_fail(3 | 16);
7474 do_test_monitor_temporary_update_fail(2 | 8 | 16);
7475 do_test_monitor_temporary_update_fail(3 | 8 | 16);
7479 fn test_monitor_update_fail_cs() {
7480 // Tests handling of a monitor update failure when processing an incoming commitment_signed
7481 let mut nodes = create_network(2);
7482 create_announced_chan_between_nodes(&nodes, 0, 1);
7484 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7485 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7486 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
7487 check_added_monitors!(nodes[0], 1);
7489 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7492 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7493 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() {
7494 assert_eq!(err, "Failed to update ChannelMonitor");
7495 } else { panic!(); }
7496 check_added_monitors!(nodes[1], 1);
7497 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7499 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
7500 nodes[1].node.test_restore_channel_monitor();
7501 check_added_monitors!(nodes[1], 1);
7502 let responses = nodes[1].node.get_and_clear_pending_msg_events();
7503 assert_eq!(responses.len(), 2);
7505 match responses[0] {
7506 MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
7507 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7508 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
7509 check_added_monitors!(nodes[0], 1);
7511 _ => panic!("Unexpected event"),
7513 match responses[1] {
7514 MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
7515 assert!(updates.update_add_htlcs.is_empty());
7516 assert!(updates.update_fulfill_htlcs.is_empty());
7517 assert!(updates.update_fail_htlcs.is_empty());
7518 assert!(updates.update_fail_malformed_htlcs.is_empty());
7519 assert!(updates.update_fee.is_none());
7520 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7522 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7523 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() {
7524 assert_eq!(err, "Failed to update ChannelMonitor");
7525 } else { panic!(); }
7526 check_added_monitors!(nodes[0], 1);
7527 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7529 _ => panic!("Unexpected event"),
7532 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7533 nodes[0].node.test_restore_channel_monitor();
7534 check_added_monitors!(nodes[0], 1);
7536 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7537 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
7538 check_added_monitors!(nodes[1], 1);
7540 let mut events = nodes[1].node.get_and_clear_pending_events();
7541 assert_eq!(events.len(), 1);
7543 Event::PendingHTLCsForwardable { .. } => { },
7544 _ => panic!("Unexpected event"),
7546 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7547 nodes[1].node.process_pending_htlc_forwards();
7549 events = nodes[1].node.get_and_clear_pending_events();
7550 assert_eq!(events.len(), 1);
7552 Event::PaymentReceived { payment_hash, amt } => {
7553 assert_eq!(payment_hash, our_payment_hash);
7554 assert_eq!(amt, 1000000);
7556 _ => panic!("Unexpected event"),
7559 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7562 fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
7563 // Tests handling of a monitor update failure when processing an incoming RAA
7564 let mut nodes = create_network(3);
7565 create_announced_chan_between_nodes(&nodes, 0, 1);
7566 create_announced_chan_between_nodes(&nodes, 1, 2);
7568 // Rebalance a bit so that we can send backwards from 2 to 1.
7569 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
7571 // Route a first payment that we'll fail backwards
7572 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
7574 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
7575 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
7576 check_added_monitors!(nodes[2], 1);
7578 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
7579 assert!(updates.update_add_htlcs.is_empty());
7580 assert!(updates.update_fulfill_htlcs.is_empty());
7581 assert_eq!(updates.update_fail_htlcs.len(), 1);
7582 assert!(updates.update_fail_malformed_htlcs.is_empty());
7583 assert!(updates.update_fee.is_none());
7584 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
7586 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
7587 check_added_monitors!(nodes[0], 0);
7589 // While the second channel is AwaitingRAA, forward a second payment to get it into the
7591 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7592 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7593 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
7594 check_added_monitors!(nodes[0], 1);
7596 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7597 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7598 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
7600 let events_1 = nodes[1].node.get_and_clear_pending_events();
7601 assert_eq!(events_1.len(), 1);
7603 Event::PendingHTLCsForwardable { .. } => { },
7604 _ => panic!("Unexpected event"),
7607 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7608 nodes[1].node.process_pending_htlc_forwards();
7609 check_added_monitors!(nodes[1], 0);
7610 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7612 // Now fail monitor updating.
7613 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7614 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() {
7615 assert_eq!(err, "Failed to update ChannelMonitor");
7616 } else { panic!(); }
7617 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7618 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7619 check_added_monitors!(nodes[1], 1);
7621 // Attempt to forward a third payment but fail due to the second channel being unavailable
7624 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
7625 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7626 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
7627 check_added_monitors!(nodes[0], 1);
7629 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
7630 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7631 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7632 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
7633 check_added_monitors!(nodes[1], 0);
7635 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7636 assert_eq!(events_2.len(), 1);
7637 match events_2.remove(0) {
7638 MessageSendEvent::UpdateHTLCs { node_id, updates } => {
7639 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7640 assert!(updates.update_fulfill_htlcs.is_empty());
7641 assert_eq!(updates.update_fail_htlcs.len(), 1);
7642 assert!(updates.update_fail_malformed_htlcs.is_empty());
7643 assert!(updates.update_add_htlcs.is_empty());
7644 assert!(updates.update_fee.is_none());
7646 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
7647 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
7649 let events = nodes[0].node.get_and_clear_pending_events();
7650 assert_eq!(events.len(), 1);
7651 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events[0] {
7652 assert_eq!(payment_hash, payment_hash_3);
7653 assert!(!rejected_by_dest);
7654 } else { panic!("Unexpected event!"); }
7656 _ => panic!("Unexpected event type!"),
7659 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
7660 // Try to route another payment backwards from 2 to make sure 1 holds off on responding
7661 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
7662 let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7663 nodes[2].node.send_payment(route, payment_hash_4).unwrap();
7664 check_added_monitors!(nodes[2], 1);
7666 send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
7667 nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7668 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) {
7669 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7670 } else { panic!(); }
7671 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7672 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7673 (Some(payment_preimage_4), Some(payment_hash_4))
7674 } else { (None, None) };
7676 // Restore monitor updating, ensuring we immediately get a fail-back update and a
7677 // update_add update.
7678 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
7679 nodes[1].node.test_restore_channel_monitor();
7680 check_added_monitors!(nodes[1], 2);
7682 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7683 if test_ignore_second_cs {
7684 assert_eq!(events_3.len(), 3);
7686 assert_eq!(events_3.len(), 2);
7689 // Note that the ordering of the events for different nodes is non-prescriptive, though the
7690 // ordering of the two events that both go to nodes[2] have to stay in the same order.
7691 let messages_a = match events_3.pop().unwrap() {
7692 MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
7693 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7694 assert!(updates.update_fulfill_htlcs.is_empty());
7695 assert_eq!(updates.update_fail_htlcs.len(), 1);
7696 assert!(updates.update_fail_malformed_htlcs.is_empty());
7697 assert!(updates.update_add_htlcs.is_empty());
7698 assert!(updates.update_fee.is_none());
7699 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
7701 _ => panic!("Unexpected event type!"),
7703 let raa = if test_ignore_second_cs {
7704 match events_3.remove(1) {
7705 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
7706 assert_eq!(node_id, nodes[2].node.get_our_node_id());
7709 _ => panic!("Unexpected event"),
7712 let send_event_b = SendEvent::from_event(events_3.remove(0));
7713 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
7715 // Now deliver the new messages...
7717 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
7718 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
7719 let events_4 = nodes[0].node.get_and_clear_pending_events();
7720 assert_eq!(events_4.len(), 1);
7721 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events_4[0] {
7722 assert_eq!(payment_hash, payment_hash_1);
7723 assert!(rejected_by_dest);
7724 } else { panic!("Unexpected event!"); }
7726 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
7727 if test_ignore_second_cs {
7728 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
7729 check_added_monitors!(nodes[2], 1);
7730 let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7731 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
7732 check_added_monitors!(nodes[2], 1);
7733 let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
7734 assert!(bs_cs.update_add_htlcs.is_empty());
7735 assert!(bs_cs.update_fail_htlcs.is_empty());
7736 assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
7737 assert!(bs_cs.update_fulfill_htlcs.is_empty());
7738 assert!(bs_cs.update_fee.is_none());
7740 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7741 check_added_monitors!(nodes[1], 1);
7742 let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
7743 assert!(as_cs.update_add_htlcs.is_empty());
7744 assert!(as_cs.update_fail_htlcs.is_empty());
7745 assert!(as_cs.update_fail_malformed_htlcs.is_empty());
7746 assert!(as_cs.update_fulfill_htlcs.is_empty());
7747 assert!(as_cs.update_fee.is_none());
7749 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
7750 check_added_monitors!(nodes[1], 1);
7751 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
7753 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
7754 check_added_monitors!(nodes[2], 1);
7755 let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7757 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
7758 check_added_monitors!(nodes[2], 1);
7759 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
7761 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
7762 check_added_monitors!(nodes[1], 1);
7763 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7765 commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
7768 let events_5 = nodes[2].node.get_and_clear_pending_events();
7769 assert_eq!(events_5.len(), 1);
7771 Event::PendingHTLCsForwardable { .. } => { },
7772 _ => panic!("Unexpected event"),
7775 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
7776 nodes[2].node.process_pending_htlc_forwards();
7778 let events_6 = nodes[2].node.get_and_clear_pending_events();
7779 assert_eq!(events_6.len(), 1);
7781 Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
7782 _ => panic!("Unexpected event"),
7785 if test_ignore_second_cs {
7786 let events_7 = nodes[1].node.get_and_clear_pending_events();
7787 assert_eq!(events_7.len(), 1);
7789 Event::PendingHTLCsForwardable { .. } => { },
7790 _ => panic!("Unexpected event"),
7793 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7794 nodes[1].node.process_pending_htlc_forwards();
7795 check_added_monitors!(nodes[1], 1);
7797 send_event = SendEvent::from_node(&nodes[1]);
7798 assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
7799 assert_eq!(send_event.msgs.len(), 1);
7800 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
7801 commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
7803 let events_8 = nodes[0].node.get_and_clear_pending_events();
7804 assert_eq!(events_8.len(), 1);
7806 Event::PendingHTLCsForwardable { .. } => { },
7807 _ => panic!("Unexpected event"),
7810 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
7811 nodes[0].node.process_pending_htlc_forwards();
7813 let events_9 = nodes[0].node.get_and_clear_pending_events();
7814 assert_eq!(events_9.len(), 1);
7816 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
7817 _ => panic!("Unexpected event"),
7819 claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
7822 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
7826 fn test_monitor_update_fail_raa() {
7827 do_test_monitor_update_fail_raa(false);
7828 do_test_monitor_update_fail_raa(true);
7832 fn test_monitor_update_fail_reestablish() {
7833 // Simple test for message retransmission after monitor update failure on
7834 // channel_reestablish generating a monitor update (which comes from freeing holding cell
7836 let mut nodes = create_network(3);
7837 create_announced_chan_between_nodes(&nodes, 0, 1);
7838 create_announced_chan_between_nodes(&nodes, 1, 2);
7840 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
7842 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7843 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7845 assert!(nodes[2].node.claim_funds(our_payment_preimage));
7846 check_added_monitors!(nodes[2], 1);
7847 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
7848 assert!(updates.update_add_htlcs.is_empty());
7849 assert!(updates.update_fail_htlcs.is_empty());
7850 assert!(updates.update_fail_malformed_htlcs.is_empty());
7851 assert!(updates.update_fee.is_none());
7852 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7853 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
7854 check_added_monitors!(nodes[1], 1);
7855 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7856 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
7858 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7859 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7860 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7862 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7863 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7865 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
7867 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() {
7868 assert_eq!(err, "Failed to update ChannelMonitor");
7869 } else { panic!(); }
7870 check_added_monitors!(nodes[1], 1);
7872 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7873 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7875 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7876 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7878 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
7879 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
7881 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
7883 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
7884 check_added_monitors!(nodes[1], 0);
7885 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7887 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
7888 nodes[1].node.test_restore_channel_monitor();
7889 check_added_monitors!(nodes[1], 1);
7891 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7892 assert!(updates.update_add_htlcs.is_empty());
7893 assert!(updates.update_fail_htlcs.is_empty());
7894 assert!(updates.update_fail_malformed_htlcs.is_empty());
7895 assert!(updates.update_fee.is_none());
7896 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7897 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
7898 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
7900 let events = nodes[0].node.get_and_clear_pending_events();
7901 assert_eq!(events.len(), 1);
7903 Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
7904 _ => panic!("Unexpected event"),
7909 fn test_invalid_channel_announcement() {
7910 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
7911 let secp_ctx = Secp256k1::new();
7912 let nodes = create_network(2);
7914 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
7916 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
7917 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
7918 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
7919 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
7921 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 } );
7923 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
7924 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
7926 let as_network_key = nodes[0].node.get_our_node_id();
7927 let bs_network_key = nodes[1].node.get_our_node_id();
7929 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
7931 let mut chan_announcement;
7933 macro_rules! dummy_unsigned_msg {
7935 msgs::UnsignedChannelAnnouncement {
7936 features: msgs::GlobalFeatures::new(),
7937 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
7938 short_channel_id: as_chan.get_short_channel_id().unwrap(),
7939 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
7940 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
7941 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
7942 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
7943 excess_data: Vec::new(),
7948 macro_rules! sign_msg {
7949 ($unsigned_msg: expr) => {
7950 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
7951 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
7952 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
7953 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
7954 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
7955 chan_announcement = msgs::ChannelAnnouncement {
7956 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
7957 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
7958 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
7959 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
7960 contents: $unsigned_msg
7965 let unsigned_msg = dummy_unsigned_msg!();
7966 sign_msg!(unsigned_msg);
7967 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
7968 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 } );
7970 // Configured with Network::Testnet
7971 let mut unsigned_msg = dummy_unsigned_msg!();
7972 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
7973 sign_msg!(unsigned_msg);
7974 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
7976 let mut unsigned_msg = dummy_unsigned_msg!();
7977 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
7978 sign_msg!(unsigned_msg);
7979 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
7982 struct VecWriter(Vec<u8>);
7983 impl Writer for VecWriter {
7984 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
7985 self.0.extend_from_slice(buf);
7988 fn size_hint(&mut self, size: usize) {
7989 self.0.reserve_exact(size);
7994 fn test_no_txn_manager_serialize_deserialize() {
7995 let mut nodes = create_network(2);
7997 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7999 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8001 let nodes_0_serialized = nodes[0].node.encode();
8002 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8003 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8005 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())));
8006 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8007 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8008 assert!(chan_0_monitor_read.is_empty());
8010 let mut nodes_0_read = &nodes_0_serialized[..];
8011 let config = UserConfig::new();
8012 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8013 let (_, nodes_0_deserialized) = {
8014 let mut channel_monitors = HashMap::new();
8015 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8016 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8017 default_config: config,
8019 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8020 monitor: nodes[0].chan_monitor.clone(),
8021 chain_monitor: nodes[0].chain_monitor.clone(),
8022 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8023 logger: Arc::new(test_utils::TestLogger::new()),
8024 channel_monitors: &channel_monitors,
8027 assert!(nodes_0_read.is_empty());
8029 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8030 nodes[0].node = Arc::new(nodes_0_deserialized);
8031 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8032 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8033 assert_eq!(nodes[0].node.list_channels().len(), 1);
8034 check_added_monitors!(nodes[0], 1);
8036 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8037 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8038 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8039 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8041 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8042 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8043 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8044 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8046 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8047 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8048 for node in nodes.iter() {
8049 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8050 node.router.handle_channel_update(&as_update).unwrap();
8051 node.router.handle_channel_update(&bs_update).unwrap();
8054 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8058 fn test_simple_manager_serialize_deserialize() {
8059 let mut nodes = create_network(2);
8060 create_announced_chan_between_nodes(&nodes, 0, 1);
8062 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8063 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8065 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8067 let nodes_0_serialized = nodes[0].node.encode();
8068 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8069 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8071 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())));
8072 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8073 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8074 assert!(chan_0_monitor_read.is_empty());
8076 let mut nodes_0_read = &nodes_0_serialized[..];
8077 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8078 let (_, nodes_0_deserialized) = {
8079 let mut channel_monitors = HashMap::new();
8080 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8081 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8082 default_config: UserConfig::new(),
8084 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8085 monitor: nodes[0].chan_monitor.clone(),
8086 chain_monitor: nodes[0].chain_monitor.clone(),
8087 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8088 logger: Arc::new(test_utils::TestLogger::new()),
8089 channel_monitors: &channel_monitors,
8092 assert!(nodes_0_read.is_empty());
8094 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8095 nodes[0].node = Arc::new(nodes_0_deserialized);
8096 check_added_monitors!(nodes[0], 1);
8098 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8100 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8101 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8105 fn test_manager_serialize_deserialize_inconsistent_monitor() {
8106 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8107 let mut nodes = create_network(4);
8108 create_announced_chan_between_nodes(&nodes, 0, 1);
8109 create_announced_chan_between_nodes(&nodes, 2, 0);
8110 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8112 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8114 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8115 let nodes_0_serialized = nodes[0].node.encode();
8117 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8118 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8119 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8120 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8122 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8124 let mut node_0_monitors_serialized = Vec::new();
8125 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8126 let mut writer = VecWriter(Vec::new());
8127 monitor.1.write_for_disk(&mut writer).unwrap();
8128 node_0_monitors_serialized.push(writer.0);
8131 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())));
8132 let mut node_0_monitors = Vec::new();
8133 for serialized in node_0_monitors_serialized.iter() {
8134 let mut read = &serialized[..];
8135 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8136 assert!(read.is_empty());
8137 node_0_monitors.push(monitor);
8140 let mut nodes_0_read = &nodes_0_serialized[..];
8141 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8142 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8143 default_config: UserConfig::new(),
8145 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8146 monitor: nodes[0].chan_monitor.clone(),
8147 chain_monitor: nodes[0].chain_monitor.clone(),
8148 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8149 logger: Arc::new(test_utils::TestLogger::new()),
8150 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8152 assert!(nodes_0_read.is_empty());
8154 { // Channel close should result in a commitment tx and an HTLC tx
8155 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8156 assert_eq!(txn.len(), 2);
8157 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8158 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8161 for monitor in node_0_monitors.drain(..) {
8162 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8163 check_added_monitors!(nodes[0], 1);
8165 nodes[0].node = Arc::new(nodes_0_deserialized);
8167 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8168 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8169 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8170 //... and we can even still claim the payment!
8171 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8173 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8174 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8175 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8176 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) {
8177 assert_eq!(msg.channel_id, channel_id);
8178 } else { panic!("Unexpected result"); }
8181 macro_rules! check_spendable_outputs {
8182 ($node: expr, $der_idx: expr) => {
8184 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8185 let mut txn = Vec::new();
8186 for event in events {
8188 Event::SpendableOutputs { ref outputs } => {
8189 for outp in outputs {
8191 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8193 previous_output: outpoint.clone(),
8194 script_sig: Script::new(),
8196 witness: Vec::new(),
8199 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8200 value: output.value,
8202 let mut spend_tx = Transaction {
8208 let secp_ctx = Secp256k1::new();
8209 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8210 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8211 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8212 let remotesig = secp_ctx.sign(&sighash, key);
8213 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8214 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8215 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8218 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8220 previous_output: outpoint.clone(),
8221 script_sig: Script::new(),
8222 sequence: *to_self_delay as u32,
8223 witness: Vec::new(),
8226 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8227 value: output.value,
8229 let mut spend_tx = Transaction {
8235 let secp_ctx = Secp256k1::new();
8236 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8237 let local_delaysig = secp_ctx.sign(&sighash, key);
8238 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8239 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8240 spend_tx.input[0].witness.push(vec!(0));
8241 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8244 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8245 let secp_ctx = Secp256k1::new();
8247 previous_output: outpoint.clone(),
8248 script_sig: Script::new(),
8250 witness: Vec::new(),
8253 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8254 value: output.value,
8256 let mut spend_tx = Transaction {
8260 output: vec![outp.clone()],
8263 match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8265 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8267 Err(_) => panic!("Your RNG is busted"),
8270 Err(_) => panic!("Your rng is busted"),
8273 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8274 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8275 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8276 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8277 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8278 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8279 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8285 _ => panic!("Unexpected event"),
8294 fn test_claim_sizeable_push_msat() {
8295 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8296 let nodes = create_network(2);
8298 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8299 nodes[1].node.force_close_channel(&chan.2);
8300 let events = nodes[1].node.get_and_clear_pending_msg_events();
8302 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8303 _ => panic!("Unexpected event"),
8305 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8306 assert_eq!(node_txn.len(), 1);
8307 check_spends!(node_txn[0], chan.3.clone());
8308 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
8310 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8311 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8312 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8313 assert_eq!(spend_txn.len(), 1);
8314 check_spends!(spend_txn[0], node_txn[0].clone());
8318 fn test_claim_on_remote_sizeable_push_msat() {
8319 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8320 // to_remote output is encumbered by a P2WPKH
8322 let nodes = create_network(2);
8324 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8325 nodes[0].node.force_close_channel(&chan.2);
8326 let events = nodes[0].node.get_and_clear_pending_msg_events();
8328 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8329 _ => panic!("Unexpected event"),
8331 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8332 assert_eq!(node_txn.len(), 1);
8333 check_spends!(node_txn[0], chan.3.clone());
8334 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
8336 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8337 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8338 let events = nodes[1].node.get_and_clear_pending_msg_events();
8340 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8341 _ => panic!("Unexpected event"),
8343 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8344 assert_eq!(spend_txn.len(), 2);
8345 assert_eq!(spend_txn[0], spend_txn[1]);
8346 check_spends!(spend_txn[0], node_txn[0].clone());
8350 fn test_claim_on_remote_revoked_sizeable_push_msat() {
8351 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8352 // to_remote output is encumbered by a P2WPKH
8354 let nodes = create_network(2);
8356 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8357 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8358 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8359 assert_eq!(revoked_local_txn[0].input.len(), 1);
8360 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8362 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8363 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8364 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8365 let events = nodes[1].node.get_and_clear_pending_msg_events();
8367 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8368 _ => panic!("Unexpected event"),
8370 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8371 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8372 assert_eq!(spend_txn.len(), 4);
8373 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8374 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8375 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8376 check_spends!(spend_txn[1], node_txn[0].clone());
8380 fn test_static_spendable_outputs_preimage_tx() {
8381 let nodes = create_network(2);
8383 // Create some initial channels
8384 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8386 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8388 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8389 assert_eq!(commitment_tx[0].input.len(), 1);
8390 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8392 // Settle A's commitment tx on B's chain
8393 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8394 assert!(nodes[1].node.claim_funds(payment_preimage));
8395 check_added_monitors!(nodes[1], 1);
8396 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8397 let events = nodes[1].node.get_and_clear_pending_msg_events();
8399 MessageSendEvent::UpdateHTLCs { .. } => {},
8400 _ => panic!("Unexpected event"),
8403 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8404 _ => panic!("Unexepected event"),
8407 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8408 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8409 check_spends!(node_txn[0], commitment_tx[0].clone());
8410 assert_eq!(node_txn[0], node_txn[2]);
8411 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
8412 check_spends!(node_txn[1], chan_1.3.clone());
8414 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8415 assert_eq!(spend_txn.len(), 2);
8416 assert_eq!(spend_txn[0], spend_txn[1]);
8417 check_spends!(spend_txn[0], node_txn[0].clone());
8421 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8422 let nodes = create_network(2);
8424 // Create some initial channels
8425 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8427 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8428 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8429 assert_eq!(revoked_local_txn[0].input.len(), 1);
8430 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8432 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8434 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8435 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8436 let events = nodes[1].node.get_and_clear_pending_msg_events();
8438 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8439 _ => panic!("Unexpected event"),
8441 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8442 assert_eq!(node_txn.len(), 3);
8443 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
8444 assert_eq!(node_txn[0].input.len(), 2);
8445 check_spends!(node_txn[0], revoked_local_txn[0].clone());
8447 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8448 assert_eq!(spend_txn.len(), 2);
8449 assert_eq!(spend_txn[0], spend_txn[1]);
8450 check_spends!(spend_txn[0], node_txn[0].clone());
8454 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
8455 let nodes = create_network(2);
8457 // Create some initial channels
8458 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8460 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8461 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8462 assert_eq!(revoked_local_txn[0].input.len(), 1);
8463 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8465 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8467 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8468 // A will generate HTLC-Timeout from revoked commitment tx
8469 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8470 let events = nodes[0].node.get_and_clear_pending_msg_events();
8472 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8473 _ => panic!("Unexpected event"),
8475 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8476 assert_eq!(revoked_htlc_txn.len(), 3);
8477 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
8478 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8479 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 133);
8480 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8481 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
8483 // B will generate justice tx from A's revoked commitment/HTLC tx
8484 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8485 let events = nodes[1].node.get_and_clear_pending_msg_events();
8487 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8488 _ => panic!("Unexpected event"),
8491 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8492 assert_eq!(node_txn.len(), 4);
8493 assert_eq!(node_txn[3].input.len(), 1);
8494 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8496 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
8497 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8498 assert_eq!(spend_txn.len(), 3);
8499 assert_eq!(spend_txn[0], spend_txn[1]);
8500 check_spends!(spend_txn[0], node_txn[0].clone());
8501 check_spends!(spend_txn[2], node_txn[3].clone());
8505 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
8506 let nodes = create_network(2);
8508 // Create some initial channels
8509 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8511 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8512 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8513 assert_eq!(revoked_local_txn[0].input.len(), 1);
8514 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8516 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8518 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8519 // B will generate HTLC-Success from revoked commitment tx
8520 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8521 let events = nodes[1].node.get_and_clear_pending_msg_events();
8523 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8524 _ => panic!("Unexpected event"),
8526 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8528 assert_eq!(revoked_htlc_txn.len(), 3);
8529 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
8530 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8531 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 138);
8532 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8534 // A will generate justice tx from B's revoked commitment/HTLC tx
8535 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8536 let events = nodes[0].node.get_and_clear_pending_msg_events();
8538 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8539 _ => panic!("Unexpected event"),
8542 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8543 assert_eq!(node_txn.len(), 4);
8544 assert_eq!(node_txn[3].input.len(), 1);
8545 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8547 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
8548 let spend_txn = check_spendable_outputs!(nodes[0], 1);
8549 assert_eq!(spend_txn.len(), 5);
8550 assert_eq!(spend_txn[0], spend_txn[2]);
8551 assert_eq!(spend_txn[1], spend_txn[3]);
8552 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
8553 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
8554 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
8558 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
8559 let nodes = create_network(2);
8561 // Create some initial channels
8562 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8564 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8565 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8566 assert_eq!(local_txn[0].input.len(), 1);
8567 check_spends!(local_txn[0], chan_1.3.clone());
8569 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
8570 nodes[1].node.claim_funds(payment_preimage);
8571 check_added_monitors!(nodes[1], 1);
8572 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8573 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
8574 let events = nodes[1].node.get_and_clear_pending_msg_events();
8576 MessageSendEvent::UpdateHTLCs { .. } => {},
8577 _ => panic!("Unexpected event"),
8580 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8581 _ => panic!("Unexepected event"),
8583 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8584 assert_eq!(node_txn[0].input.len(), 1);
8585 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 138);
8586 check_spends!(node_txn[0], local_txn[0].clone());
8588 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
8589 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8590 assert_eq!(spend_txn.len(), 2);
8591 check_spends!(spend_txn[0], node_txn[0].clone());
8592 check_spends!(spend_txn[1], node_txn[2].clone());
8596 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
8597 let nodes = create_network(2);
8599 // Create some initial channels
8600 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8602 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8603 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8604 assert_eq!(local_txn[0].input.len(), 1);
8605 check_spends!(local_txn[0], chan_1.3.clone());
8607 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8608 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8609 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8610 let events = nodes[0].node.get_and_clear_pending_msg_events();
8612 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8613 _ => panic!("Unexepected event"),
8615 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8616 assert_eq!(node_txn[0].input.len(), 1);
8617 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
8618 check_spends!(node_txn[0], local_txn[0].clone());
8620 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
8621 let spend_txn = check_spendable_outputs!(nodes[0], 1);
8622 assert_eq!(spend_txn.len(), 8);
8623 assert_eq!(spend_txn[0], spend_txn[2]);
8624 assert_eq!(spend_txn[0], spend_txn[4]);
8625 assert_eq!(spend_txn[0], spend_txn[6]);
8626 assert_eq!(spend_txn[1], spend_txn[3]);
8627 assert_eq!(spend_txn[1], spend_txn[5]);
8628 assert_eq!(spend_txn[1], spend_txn[7]);
8629 check_spends!(spend_txn[0], local_txn[0].clone());
8630 check_spends!(spend_txn[1], node_txn[0].clone());
8634 fn test_static_output_closing_tx() {
8635 let nodes = create_network(2);
8637 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
8639 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
8640 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
8642 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8643 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
8644 let spend_txn = check_spendable_outputs!(nodes[0], 2);
8645 assert_eq!(spend_txn.len(), 1);
8646 check_spends!(spend_txn[0], closing_tx.clone());
8648 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
8649 let spend_txn = check_spendable_outputs!(nodes[1], 2);
8650 assert_eq!(spend_txn.len(), 1);
8651 check_spends!(spend_txn[0], closing_tx);