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
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
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);
682 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
683 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
684 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
685 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
686 //timeouts are hit and our claims confirm).
687 //TODO: In any case, we need to make sure we remove any pending htlc tracking (via
688 //fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
691 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
692 /// the chain and rejecting new HTLCs on the given channel.
693 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
694 let _ = self.total_consistency_lock.read().unwrap();
697 let mut channel_state_lock = self.channel_state.lock().unwrap();
698 let channel_state = channel_state_lock.borrow_parts();
699 if let Some(chan) = channel_state.by_id.remove(channel_id) {
700 if let Some(short_id) = chan.get_short_channel_id() {
701 channel_state.short_to_id.remove(&short_id);
708 self.finish_force_close_channel(chan.force_shutdown());
709 if let Ok(update) = self.get_channel_update(&chan) {
710 let mut channel_state = self.channel_state.lock().unwrap();
711 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
717 /// Force close all channels, immediately broadcasting the latest local commitment transaction
718 /// for each to the chain and rejecting new HTLCs on each.
719 pub fn force_close_all_channels(&self) {
720 for chan in self.list_channels() {
721 self.force_close_channel(&chan.channel_id);
726 fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
727 assert_eq!(shared_secret.len(), 32);
729 let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
730 hmac.input(&shared_secret[..]);
731 let mut res = [0; 32];
732 hmac.raw_result(&mut res);
736 let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
737 hmac.input(&shared_secret[..]);
738 let mut res = [0; 32];
739 hmac.raw_result(&mut res);
745 fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
746 assert_eq!(shared_secret.len(), 32);
747 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
748 hmac.input(&shared_secret[..]);
749 let mut res = [0; 32];
750 hmac.raw_result(&mut res);
755 fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
756 assert_eq!(shared_secret.len(), 32);
757 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
758 hmac.input(&shared_secret[..]);
759 let mut res = [0; 32];
760 hmac.raw_result(&mut res);
764 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
766 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> {
767 let mut blinded_priv = session_priv.clone();
768 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
770 for hop in route.hops.iter() {
771 let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
773 let mut sha = Sha256::new();
774 sha.input(&blinded_pub.serialize()[..]);
775 sha.input(&shared_secret[..]);
776 let mut blinding_factor = [0u8; 32];
777 sha.result(&mut blinding_factor);
779 let ephemeral_pubkey = blinded_pub;
781 blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
782 blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
784 callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
790 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
791 fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
792 let mut res = Vec::with_capacity(route.hops.len());
794 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
795 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
801 blinding_factor: _blinding_factor,
811 /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
812 fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
813 let mut cur_value_msat = 0u64;
814 let mut cur_cltv = starting_htlc_offset;
815 let mut last_short_channel_id = 0;
816 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
817 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
818 unsafe { res.set_len(route.hops.len()); }
820 for (idx, hop) in route.hops.iter().enumerate().rev() {
821 // First hop gets special values so that it can check, on receipt, that everything is
822 // exactly as it should be (and the next hop isn't trying to probe to find out if we're
823 // the intended recipient).
824 let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
825 let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
826 res[idx] = msgs::OnionHopData {
828 data: msgs::OnionRealm0HopData {
829 short_channel_id: last_short_channel_id,
830 amt_to_forward: value_msat,
831 outgoing_cltv_value: cltv,
835 cur_value_msat += hop.fee_msat;
836 if cur_value_msat >= 21000000 * 100000000 * 1000 {
837 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
839 cur_cltv += hop.cltv_expiry_delta as u32;
840 if cur_cltv >= 500000000 {
841 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
843 last_short_channel_id = hop.short_channel_id;
845 Ok((res, cur_value_msat, cur_cltv))
849 fn shift_arr_right(arr: &mut [u8; 20*65]) {
851 ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
859 fn xor_bufs(dst: &mut[u8], src: &[u8]) {
860 assert_eq!(dst.len(), src.len());
862 for i in 0..dst.len() {
867 const ZERO:[u8; 21*65] = [0; 21*65];
868 fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
869 let mut buf = Vec::with_capacity(21*65);
870 buf.resize(21*65, 0);
873 let iters = payloads.len() - 1;
874 let end_len = iters * 65;
875 let mut res = Vec::with_capacity(end_len);
876 res.resize(end_len, 0);
878 for (i, keys) in onion_keys.iter().enumerate() {
879 if i == payloads.len() - 1 { continue; }
880 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
881 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
882 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
887 let mut packet_data = [0; 20*65];
888 let mut hmac_res = [0; 32];
890 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
891 ChannelManager::shift_arr_right(&mut packet_data);
892 payload.hmac = hmac_res;
893 packet_data[0..65].copy_from_slice(&payload.encode()[..]);
895 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
896 chacha.process(&packet_data, &mut buf[0..20*65]);
897 packet_data[..].copy_from_slice(&buf[0..20*65]);
900 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
903 let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
904 hmac.input(&packet_data);
905 hmac.input(&associated_data[..]);
906 hmac.raw_result(&mut hmac_res);
911 public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
912 hop_data: packet_data,
917 /// Encrypts a failure packet. raw_packet can either be a
918 /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
919 fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
920 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
922 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
923 packet_crypted.resize(raw_packet.len(), 0);
924 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
925 chacha.process(&raw_packet, &mut packet_crypted[..]);
926 msgs::OnionErrorPacket {
927 data: packet_crypted,
931 fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
932 assert_eq!(shared_secret.len(), 32);
933 assert!(failure_data.len() <= 256 - 2);
935 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
938 let mut res = Vec::with_capacity(2 + failure_data.len());
939 res.push(((failure_type >> 8) & 0xff) as u8);
940 res.push(((failure_type >> 0) & 0xff) as u8);
941 res.extend_from_slice(&failure_data[..]);
945 let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
946 res.resize(256 - 2 - failure_data.len(), 0);
949 let mut packet = msgs::DecodedOnionErrorPacket {
951 failuremsg: failuremsg,
955 let mut hmac = Hmac::new(Sha256::new(), &um);
956 hmac.input(&packet.encode()[32..]);
957 hmac.raw_result(&mut packet.hmac);
963 fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
964 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
965 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
968 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
969 macro_rules! get_onion_hash {
972 let mut sha = Sha256::new();
973 sha.input(&msg.onion_routing_packet.hop_data);
974 let mut onion_hash = [0; 32];
975 sha.result(&mut onion_hash);
981 if let Err(_) = msg.onion_routing_packet.public_key {
982 log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
983 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
984 channel_id: msg.channel_id,
985 htlc_id: msg.htlc_id,
986 sha256_of_onion: get_onion_hash!(),
987 failure_code: 0x8000 | 0x4000 | 6,
988 })), self.channel_state.lock().unwrap());
991 let shared_secret = {
992 let mut arr = [0; 32];
993 arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
996 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
998 let mut channel_state = None;
999 macro_rules! return_err {
1000 ($msg: expr, $err_code: expr, $data: expr) => {
1002 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1003 if channel_state.is_none() {
1004 channel_state = Some(self.channel_state.lock().unwrap());
1006 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1007 channel_id: msg.channel_id,
1008 htlc_id: msg.htlc_id,
1009 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1010 })), channel_state.unwrap());
1015 if msg.onion_routing_packet.version != 0 {
1016 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1017 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1018 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1019 //receiving node would have to brute force to figure out which version was put in the
1020 //packet by the node that send us the message, in the case of hashing the hop_data, the
1021 //node knows the HMAC matched, so they already know what is there...
1022 return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1025 let mut hmac = Hmac::new(Sha256::new(), &mu);
1026 hmac.input(&msg.onion_routing_packet.hop_data);
1027 hmac.input(&msg.payment_hash);
1028 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1029 return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1032 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1033 let next_hop_data = {
1034 let mut decoded = [0; 65];
1035 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1036 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1038 let error_code = match err {
1039 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1040 _ => 0x2000 | 2, // Should never happen
1042 return_err!("Unable to decode our hop data", error_code, &[0;0]);
1048 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1050 // final_expiry_too_soon
1051 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1052 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1054 // final_incorrect_htlc_amount
1055 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1056 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1058 // final_incorrect_cltv_expiry
1059 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1060 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1063 // Note that we could obviously respond immediately with an update_fulfill_htlc
1064 // message, however that would leak that we are the recipient of this payment, so
1065 // instead we stay symmetric with the forwarding case, only responding (after a
1066 // delay) once they've send us a commitment_signed!
1068 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1070 payment_hash: msg.payment_hash.clone(),
1071 short_channel_id: 0,
1072 incoming_shared_secret: shared_secret,
1073 amt_to_forward: next_hop_data.data.amt_to_forward,
1074 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1077 let mut new_packet_data = [0; 20*65];
1078 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1079 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1081 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1083 let blinding_factor = {
1084 let mut sha = Sha256::new();
1085 sha.input(&new_pubkey.serialize()[..]);
1086 sha.input(&shared_secret);
1087 let mut res = [0u8; 32];
1088 sha.result(&mut res);
1089 match SecretKey::from_slice(&self.secp_ctx, &res) {
1091 return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1097 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1098 return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1101 let outgoing_packet = msgs::OnionPacket {
1103 public_key: Ok(new_pubkey),
1104 hop_data: new_packet_data,
1105 hmac: next_hop_data.hmac.clone(),
1108 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1109 onion_packet: Some(outgoing_packet),
1110 payment_hash: msg.payment_hash.clone(),
1111 short_channel_id: next_hop_data.data.short_channel_id,
1112 incoming_shared_secret: shared_secret,
1113 amt_to_forward: next_hop_data.data.amt_to_forward,
1114 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1118 channel_state = Some(self.channel_state.lock().unwrap());
1119 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1120 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1121 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1122 let forwarding_id = match id_option {
1123 None => { // unknown_next_peer
1124 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1126 Some(id) => id.clone(),
1128 if let Some((err, code, chan_update)) = loop {
1129 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1131 // Note that we could technically not return an error yet here and just hope
1132 // that the connection is reestablished or monitor updated by the time we get
1133 // around to doing the actual forward, but better to fail early if we can and
1134 // hopefully an attacker trying to path-trace payments cannot make this occur
1135 // on a small/per-node/per-channel scale.
1136 if !chan.is_live() { // channel_disabled
1137 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1139 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1140 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1142 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) });
1143 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1144 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())));
1146 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1147 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())));
1149 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1150 // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1151 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1152 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1154 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1155 break Some(("CLTV expiry is too far in the future", 21, None));
1160 let mut res = Vec::with_capacity(8 + 128);
1161 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1162 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1164 else if code == 0x1000 | 13 {
1165 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1167 if let Some(chan_update) = chan_update {
1168 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1170 return_err!(err, code, &res[..]);
1175 (pending_forward_info, channel_state.unwrap())
1178 /// only fails if the channel does not yet have an assigned short_id
1179 /// May be called with channel_state already locked!
1180 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1181 let short_channel_id = match chan.get_short_channel_id() {
1182 None => return Err(HandleError{err: "Channel not yet established", action: None}),
1186 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1188 let unsigned = msgs::UnsignedChannelUpdate {
1189 chain_hash: self.genesis_hash,
1190 short_channel_id: short_channel_id,
1191 timestamp: chan.get_channel_update_count(),
1192 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1193 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1194 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1195 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1196 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1197 excess_data: Vec::new(),
1200 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1201 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1203 Ok(msgs::ChannelUpdate {
1209 /// Sends a payment along a given route.
1211 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1212 /// fields for more info.
1214 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1215 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1216 /// next hop knows the preimage to payment_hash they can claim an additional amount as
1217 /// specified in the last hop in the route! Thus, you should probably do your own
1218 /// payment_preimage tracking (which you should already be doing as they represent "proof of
1219 /// payment") and prevent double-sends yourself.
1221 /// May generate a SendHTLCs message event on success, which should be relayed.
1223 /// Raises APIError::RoutError when invalid route or forward parameter
1224 /// (cltv_delta, fee, node public key) is specified.
1225 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1226 /// (including due to previous monitor update failure or new permanent monitor update failure).
1227 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1228 /// relevant updates.
1230 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1231 /// and you may wish to retry via a different route immediately.
1232 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1233 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1234 /// the payment via a different route unless you intend to pay twice!
1235 pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1236 if route.hops.len() < 1 || route.hops.len() > 20 {
1237 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1239 let our_node_id = self.get_our_node_id();
1240 for (idx, hop) in route.hops.iter().enumerate() {
1241 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1242 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1246 let session_priv = self.keys_manager.get_session_key();
1248 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1250 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1251 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1252 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1253 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1255 let _ = self.total_consistency_lock.read().unwrap();
1257 let err: Result<(), _> = loop {
1258 let mut channel_lock = self.channel_state.lock().unwrap();
1260 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1261 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1262 Some(id) => id.clone(),
1265 let channel_state = channel_lock.borrow_parts();
1266 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1268 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1269 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1271 if !chan.get().is_live() {
1272 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1274 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1275 route: route.clone(),
1276 session_priv: session_priv.clone(),
1277 first_hop_htlc_msat: htlc_msat,
1278 }, onion_packet), channel_state, chan)
1280 Some((update_add, commitment_signed, chan_monitor)) => {
1281 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1282 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1283 // Note that MonitorUpdateFailed here indicates (per function docs)
1284 // that we will resent the commitment update once we unfree monitor
1285 // updating, so we have to take special care that we don't return
1286 // something else in case we will resend later!
1287 return Err(APIError::MonitorUpdateFailed);
1290 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1291 node_id: route.hops.first().unwrap().pubkey,
1292 updates: msgs::CommitmentUpdate {
1293 update_add_htlcs: vec![update_add],
1294 update_fulfill_htlcs: Vec::new(),
1295 update_fail_htlcs: Vec::new(),
1296 update_fail_malformed_htlcs: Vec::new(),
1304 } else { unreachable!(); }
1308 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1309 Ok(_) => unreachable!(),
1311 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1313 log_error!(self, "Got bad keys: {}!", e.err);
1314 let mut channel_state = self.channel_state.lock().unwrap();
1315 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1316 node_id: route.hops.first().unwrap().pubkey,
1320 Err(APIError::ChannelUnavailable { err: e.err })
1325 /// Call this upon creation of a funding transaction for the given channel.
1327 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1328 /// or your counterparty can steal your funds!
1330 /// Panics if a funding transaction has already been provided for this channel.
1332 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1333 /// be trivially prevented by using unique funding transaction keys per-channel).
1334 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1335 let _ = self.total_consistency_lock.read().unwrap();
1337 let (chan, msg, chan_monitor) = {
1339 let mut channel_state = self.channel_state.lock().unwrap();
1340 match channel_state.by_id.remove(temporary_channel_id) {
1342 (chan.get_outbound_funding_created(funding_txo)
1343 .map_err(|e| if let ChannelError::Close(msg) = e {
1344 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1345 } else { unreachable!(); })
1351 match handle_error!(self, res, chan.get_their_node_id()) {
1352 Ok(funding_msg) => {
1353 (chan, funding_msg.0, funding_msg.1)
1356 log_error!(self, "Got bad signatures: {}!", e.err);
1357 let mut channel_state = self.channel_state.lock().unwrap();
1358 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1359 node_id: chan.get_their_node_id(),
1366 // Because we have exclusive ownership of the channel here we can release the channel_state
1367 // lock before add_update_monitor
1368 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1372 let mut channel_state = self.channel_state.lock().unwrap();
1373 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1374 node_id: chan.get_their_node_id(),
1377 match channel_state.by_id.entry(chan.channel_id()) {
1378 hash_map::Entry::Occupied(_) => {
1379 panic!("Generated duplicate funding txid?");
1381 hash_map::Entry::Vacant(e) => {
1387 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1388 if !chan.should_announce() { return None }
1390 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1392 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1394 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1395 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1397 Some(msgs::AnnouncementSignatures {
1398 channel_id: chan.channel_id(),
1399 short_channel_id: chan.get_short_channel_id().unwrap(),
1400 node_signature: our_node_sig,
1401 bitcoin_signature: our_bitcoin_sig,
1405 /// Processes HTLCs which are pending waiting on random forward delay.
1407 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1408 /// Will likely generate further events.
1409 pub fn process_pending_htlc_forwards(&self) {
1410 let _ = self.total_consistency_lock.read().unwrap();
1412 let mut new_events = Vec::new();
1413 let mut failed_forwards = Vec::new();
1415 let mut channel_state_lock = self.channel_state.lock().unwrap();
1416 let channel_state = channel_state_lock.borrow_parts();
1418 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1422 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1423 if short_chan_id != 0 {
1424 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1425 Some(chan_id) => chan_id.clone(),
1427 failed_forwards.reserve(pending_forwards.len());
1428 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1429 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1430 short_channel_id: prev_short_channel_id,
1431 htlc_id: prev_htlc_id,
1432 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1434 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1439 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1441 let mut add_htlc_msgs = Vec::new();
1442 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1443 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1444 short_channel_id: prev_short_channel_id,
1445 htlc_id: prev_htlc_id,
1446 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1448 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()) {
1450 let chan_update = self.get_channel_update(forward_chan).unwrap();
1451 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1456 Some(msg) => { add_htlc_msgs.push(msg); },
1458 // Nothing to do here...we're waiting on a remote
1459 // revoke_and_ack before we can add anymore HTLCs. The Channel
1460 // will automatically handle building the update_add_htlc and
1461 // commitment_signed messages when we can.
1462 // TODO: Do some kind of timer to set the channel as !is_live()
1463 // as we don't really want others relying on us relaying through
1464 // this channel currently :/.
1471 if !add_htlc_msgs.is_empty() {
1472 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1475 if let ChannelError::Ignore(_) = e {
1476 panic!("Stated return value requirements in send_commitment() were not met");
1478 //TODO: Handle...this is bad!
1482 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1485 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1486 node_id: forward_chan.get_their_node_id(),
1487 updates: msgs::CommitmentUpdate {
1488 update_add_htlcs: add_htlc_msgs,
1489 update_fulfill_htlcs: Vec::new(),
1490 update_fail_htlcs: Vec::new(),
1491 update_fail_malformed_htlcs: Vec::new(),
1493 commitment_signed: commitment_msg,
1498 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1499 let prev_hop_data = HTLCPreviousHopData {
1500 short_channel_id: prev_short_channel_id,
1501 htlc_id: prev_htlc_id,
1502 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1504 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1505 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1506 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1508 new_events.push(events::Event::PaymentReceived {
1509 payment_hash: forward_info.payment_hash,
1510 amt: forward_info.amt_to_forward,
1517 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1519 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1520 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() }),
1524 if new_events.is_empty() { return }
1525 let mut events = self.pending_events.lock().unwrap();
1526 events.append(&mut new_events);
1529 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1530 pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32], reason: PaymentFailReason) -> bool {
1531 let _ = self.total_consistency_lock.read().unwrap();
1533 let mut channel_state = Some(self.channel_state.lock().unwrap());
1534 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1535 if let Some(mut sources) = removed_source {
1536 for htlc_with_hash in sources.drain(..) {
1537 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1538 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() });
1544 /// Fails an HTLC backwards to the sender of it to us.
1545 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1546 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1547 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1548 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1549 /// still-available channels.
1550 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1552 HTLCSource::OutboundRoute { .. } => {
1553 mem::drop(channel_state_lock);
1554 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1555 let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1556 if let Some(update) = channel_update {
1557 self.channel_state.lock().unwrap().pending_msg_events.push(
1558 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1563 self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1564 payment_hash: payment_hash.clone(),
1565 rejected_by_dest: !payment_retryable,
1568 panic!("should have onion error packet here");
1571 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1572 let err_packet = match onion_error {
1573 HTLCFailReason::Reason { failure_code, data } => {
1574 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1575 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1577 HTLCFailReason::ErrorPacket { err } => {
1578 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1582 let channel_state = channel_state_lock.borrow_parts();
1584 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1585 Some(chan_id) => chan_id.clone(),
1589 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1590 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1591 Ok(Some((msg, commitment_msg, chan_monitor))) => {
1592 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1595 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1596 node_id: chan.get_their_node_id(),
1597 updates: msgs::CommitmentUpdate {
1598 update_add_htlcs: Vec::new(),
1599 update_fulfill_htlcs: Vec::new(),
1600 update_fail_htlcs: vec![msg],
1601 update_fail_malformed_htlcs: Vec::new(),
1603 commitment_signed: commitment_msg,
1609 //TODO: Do something with e?
1617 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1618 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1619 /// should probably kick the net layer to go send messages if this returns true!
1621 /// May panic if called except in response to a PaymentReceived event.
1622 pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1623 let mut sha = Sha256::new();
1624 sha.input(&payment_preimage);
1625 let mut payment_hash = [0; 32];
1626 sha.result(&mut payment_hash);
1628 let _ = self.total_consistency_lock.read().unwrap();
1630 let mut channel_state = Some(self.channel_state.lock().unwrap());
1631 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1632 if let Some(mut sources) = removed_source {
1633 for htlc_with_hash in sources.drain(..) {
1634 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1635 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1640 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1642 HTLCSource::OutboundRoute { .. } => {
1643 mem::drop(channel_state_lock);
1644 let mut pending_events = self.pending_events.lock().unwrap();
1645 pending_events.push(events::Event::PaymentSent {
1649 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1650 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1651 let channel_state = channel_state_lock.borrow_parts();
1653 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1654 Some(chan_id) => chan_id.clone(),
1656 // TODO: There is probably a channel manager somewhere that needs to
1657 // learn the preimage as the channel already hit the chain and that's
1663 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1664 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1665 Ok((msgs, monitor_option)) => {
1666 if let Some(chan_monitor) = monitor_option {
1667 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1668 unimplemented!();// but def dont push the event...
1671 if let Some((msg, commitment_signed)) = msgs {
1672 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1673 node_id: chan.get_their_node_id(),
1674 updates: msgs::CommitmentUpdate {
1675 update_add_htlcs: Vec::new(),
1676 update_fulfill_htlcs: vec![msg],
1677 update_fail_htlcs: Vec::new(),
1678 update_fail_malformed_htlcs: Vec::new(),
1686 // TODO: There is probably a channel manager somewhere that needs to
1687 // learn the preimage as the channel may be about to hit the chain.
1688 //TODO: Do something with e?
1696 /// Gets the node_id held by this ChannelManager
1697 pub fn get_our_node_id(&self) -> PublicKey {
1698 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1701 /// Used to restore channels to normal operation after a
1702 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1704 pub fn test_restore_channel_monitor(&self) {
1705 let mut close_results = Vec::new();
1706 let mut htlc_forwards = Vec::new();
1707 let mut htlc_failures = Vec::new();
1708 let _ = self.total_consistency_lock.read().unwrap();
1711 let mut channel_lock = self.channel_state.lock().unwrap();
1712 let channel_state = channel_lock.borrow_parts();
1713 let short_to_id = channel_state.short_to_id;
1714 let pending_msg_events = channel_state.pending_msg_events;
1715 channel_state.by_id.retain(|_, channel| {
1716 if channel.is_awaiting_monitor_update() {
1717 let chan_monitor = channel.channel_monitor();
1718 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1720 ChannelMonitorUpdateErr::PermanentFailure => {
1721 // TODO: There may be some pending HTLCs that we intended to fail
1722 // backwards when a monitor update failed. We should make sure
1723 // knowledge of those gets moved into the appropriate in-memory
1724 // ChannelMonitor and they get failed backwards once we get
1725 // on-chain confirmations.
1726 // Note I think #198 addresses this, so once its merged a test
1727 // should be written.
1728 if let Some(short_id) = channel.get_short_channel_id() {
1729 short_to_id.remove(&short_id);
1731 close_results.push(channel.force_shutdown());
1732 if let Ok(update) = self.get_channel_update(&channel) {
1733 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1739 ChannelMonitorUpdateErr::TemporaryFailure => true,
1742 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1743 if !pending_forwards.is_empty() {
1744 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1746 htlc_failures.append(&mut pending_failures);
1748 macro_rules! handle_cs { () => {
1749 if let Some(update) = commitment_update {
1750 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1751 node_id: channel.get_their_node_id(),
1756 macro_rules! handle_raa { () => {
1757 if let Some(revoke_and_ack) = raa {
1758 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1759 node_id: channel.get_their_node_id(),
1760 msg: revoke_and_ack,
1765 RAACommitmentOrder::CommitmentFirst => {
1769 RAACommitmentOrder::RevokeAndACKFirst => {
1780 for failure in htlc_failures.drain(..) {
1781 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1783 self.forward_htlcs(&mut htlc_forwards[..]);
1785 for res in close_results.drain(..) {
1786 self.finish_force_close_channel(res);
1790 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1791 if msg.chain_hash != self.genesis_hash {
1792 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1795 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)
1796 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1797 let mut channel_state_lock = self.channel_state.lock().unwrap();
1798 let channel_state = channel_state_lock.borrow_parts();
1799 match channel_state.by_id.entry(channel.channel_id()) {
1800 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1801 hash_map::Entry::Vacant(entry) => {
1802 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1803 node_id: their_node_id.clone(),
1804 msg: channel.get_accept_channel(),
1806 entry.insert(channel);
1812 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1813 let (value, output_script, user_id) = {
1814 let mut channel_lock = self.channel_state.lock().unwrap();
1815 let channel_state = channel_lock.borrow_parts();
1816 match channel_state.by_id.entry(msg.temporary_channel_id) {
1817 hash_map::Entry::Occupied(mut chan) => {
1818 if chan.get().get_their_node_id() != *their_node_id {
1819 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1820 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1822 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1823 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1825 //TODO: same as above
1826 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1829 let mut pending_events = self.pending_events.lock().unwrap();
1830 pending_events.push(events::Event::FundingGenerationReady {
1831 temporary_channel_id: msg.temporary_channel_id,
1832 channel_value_satoshis: value,
1833 output_script: output_script,
1834 user_channel_id: user_id,
1839 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1840 let ((funding_msg, monitor_update), chan) = {
1841 let mut channel_lock = self.channel_state.lock().unwrap();
1842 let channel_state = channel_lock.borrow_parts();
1843 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1844 hash_map::Entry::Occupied(mut chan) => {
1845 if chan.get().get_their_node_id() != *their_node_id {
1846 //TODO: here and below MsgHandleErrInternal, #153 case
1847 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1849 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1851 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1854 // Because we have exclusive ownership of the channel here we can release the channel_state
1855 // lock before add_update_monitor
1856 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1859 let mut channel_state_lock = self.channel_state.lock().unwrap();
1860 let channel_state = channel_state_lock.borrow_parts();
1861 match channel_state.by_id.entry(funding_msg.channel_id) {
1862 hash_map::Entry::Occupied(_) => {
1863 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1865 hash_map::Entry::Vacant(e) => {
1866 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1867 node_id: their_node_id.clone(),
1876 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1877 let (funding_txo, user_id) = {
1878 let mut channel_lock = self.channel_state.lock().unwrap();
1879 let channel_state = channel_lock.borrow_parts();
1880 match channel_state.by_id.entry(msg.channel_id) {
1881 hash_map::Entry::Occupied(mut chan) => {
1882 if chan.get().get_their_node_id() != *their_node_id {
1883 //TODO: here and below MsgHandleErrInternal, #153 case
1884 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1886 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1887 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1890 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1892 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1895 let mut pending_events = self.pending_events.lock().unwrap();
1896 pending_events.push(events::Event::FundingBroadcastSafe {
1897 funding_txo: funding_txo,
1898 user_channel_id: user_id,
1903 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1904 let mut channel_state_lock = self.channel_state.lock().unwrap();
1905 let channel_state = channel_state_lock.borrow_parts();
1906 match channel_state.by_id.entry(msg.channel_id) {
1907 hash_map::Entry::Occupied(mut chan) => {
1908 if chan.get().get_their_node_id() != *their_node_id {
1909 //TODO: here and below MsgHandleErrInternal, #153 case
1910 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1912 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1913 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1914 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1915 node_id: their_node_id.clone(),
1916 msg: announcement_sigs,
1921 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1925 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1926 let (mut dropped_htlcs, chan_option) = {
1927 let mut channel_state_lock = self.channel_state.lock().unwrap();
1928 let channel_state = channel_state_lock.borrow_parts();
1930 match channel_state.by_id.entry(msg.channel_id.clone()) {
1931 hash_map::Entry::Occupied(mut chan_entry) => {
1932 if chan_entry.get().get_their_node_id() != *their_node_id {
1933 //TODO: here and below MsgHandleErrInternal, #153 case
1934 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1936 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1937 if let Some(msg) = shutdown {
1938 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1939 node_id: their_node_id.clone(),
1943 if let Some(msg) = closing_signed {
1944 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1945 node_id: their_node_id.clone(),
1949 if chan_entry.get().is_shutdown() {
1950 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1951 channel_state.short_to_id.remove(&short_id);
1953 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1954 } else { (dropped_htlcs, None) }
1956 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1959 for htlc_source in dropped_htlcs.drain(..) {
1960 // unknown_next_peer...I dunno who that is anymore....
1961 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() });
1963 if let Some(chan) = chan_option {
1964 if let Ok(update) = self.get_channel_update(&chan) {
1965 let mut channel_state = self.channel_state.lock().unwrap();
1966 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1974 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1975 let (tx, chan_option) = {
1976 let mut channel_state_lock = self.channel_state.lock().unwrap();
1977 let channel_state = channel_state_lock.borrow_parts();
1978 match channel_state.by_id.entry(msg.channel_id.clone()) {
1979 hash_map::Entry::Occupied(mut chan_entry) => {
1980 if chan_entry.get().get_their_node_id() != *their_node_id {
1981 //TODO: here and below MsgHandleErrInternal, #153 case
1982 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1984 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1985 if let Some(msg) = closing_signed {
1986 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1987 node_id: their_node_id.clone(),
1992 // We're done with this channel, we've got a signed closing transaction and
1993 // will send the closing_signed back to the remote peer upon return. This
1994 // also implies there are no pending HTLCs left on the channel, so we can
1995 // fully delete it from tracking (the channel monitor is still around to
1996 // watch for old state broadcasts)!
1997 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1998 channel_state.short_to_id.remove(&short_id);
2000 (tx, Some(chan_entry.remove_entry().1))
2001 } else { (tx, None) }
2003 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2006 if let Some(broadcast_tx) = tx {
2007 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2009 if let Some(chan) = chan_option {
2010 if let Ok(update) = self.get_channel_update(&chan) {
2011 let mut channel_state = self.channel_state.lock().unwrap();
2012 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2020 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2021 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2022 //determine the state of the payment based on our response/if we forward anything/the time
2023 //we take to respond. We should take care to avoid allowing such an attack.
2025 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2026 //us repeatedly garbled in different ways, and compare our error messages, which are
2027 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2028 //but we should prevent it anyway.
2030 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2031 let channel_state = channel_state_lock.borrow_parts();
2033 match channel_state.by_id.entry(msg.channel_id) {
2034 hash_map::Entry::Occupied(mut chan) => {
2035 if chan.get().get_their_node_id() != *their_node_id {
2036 //TODO: here MsgHandleErrInternal, #153 case
2037 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2039 if !chan.get().is_usable() {
2040 // If the update_add is completely bogus, the call will Err and we will close,
2041 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2042 // want to reject the new HTLC and fail it backwards instead of forwarding.
2043 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2044 let chan_update = self.get_channel_update(chan.get());
2045 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2046 channel_id: msg.channel_id,
2047 htlc_id: msg.htlc_id,
2048 reason: if let Ok(update) = chan_update {
2049 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2051 // This can only happen if the channel isn't in the fully-funded
2052 // state yet, implying our counterparty is trying to route payments
2053 // over the channel back to themselves (cause no one else should
2054 // know the short_id is a lightning channel yet). We should have no
2055 // problem just calling this unknown_next_peer
2056 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2061 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2063 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2068 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2069 let mut channel_lock = self.channel_state.lock().unwrap();
2071 let channel_state = channel_lock.borrow_parts();
2072 match channel_state.by_id.entry(msg.channel_id) {
2073 hash_map::Entry::Occupied(mut chan) => {
2074 if chan.get().get_their_node_id() != *their_node_id {
2075 //TODO: here and below MsgHandleErrInternal, #153 case
2076 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2078 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2080 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2083 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2087 // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2088 // indicating that the payment itself failed
2089 fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2090 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2091 macro_rules! onion_failure_log {
2092 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2093 log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2095 ( $error_code_textual: expr, $error_code: expr ) => {
2096 log_trace!(self, "{}({})", $error_code_textual, $error_code);
2100 const BADONION: u16 = 0x8000;
2101 const PERM: u16 = 0x4000;
2102 const UPDATE: u16 = 0x1000;
2105 let mut htlc_msat = *first_hop_htlc_msat;
2107 // Handle packed channel/node updates for passing back for the route handler
2108 Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2109 if res.is_some() { return; }
2111 let incoming_htlc_msat = htlc_msat;
2112 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2113 htlc_msat = amt_to_forward;
2115 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2117 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2118 decryption_tmp.resize(packet_decrypted.len(), 0);
2119 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2120 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2121 packet_decrypted = decryption_tmp;
2123 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2125 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2126 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2127 let mut hmac = Hmac::new(Sha256::new(), &um);
2128 hmac.input(&err_packet.encode()[32..]);
2129 let mut calc_tag = [0u8; 32];
2130 hmac.raw_result(&mut calc_tag);
2132 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2133 if err_packet.failuremsg.len() < 2 {
2134 // Useless packet that we can't use but it passed HMAC, so it
2135 // definitely came from the peer in question
2136 res = Some((None, !is_from_final_node));
2138 let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2140 match error_code & 0xff {
2142 // either from an intermediate or final node
2143 // invalid_realm(PERM|1),
2144 // temporary_node_failure(NODE|2)
2145 // permanent_node_failure(PERM|NODE|2)
2146 // required_node_feature_mssing(PERM|NODE|3)
2147 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2148 node_id: route_hop.pubkey,
2149 is_permanent: error_code & PERM == PERM,
2150 }), !(error_code & PERM == PERM && is_from_final_node)));
2151 // node returning invalid_realm is removed from network_map,
2152 // although NODE flag is not set, TODO: or remove channel only?
2153 // retry payment when removed node is not a final node
2159 if is_from_final_node {
2160 let payment_retryable = match error_code {
2161 c if c == PERM|15 => false, // unknown_payment_hash
2162 c if c == PERM|16 => false, // incorrect_payment_amount
2163 17 => true, // final_expiry_too_soon
2164 18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2165 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2168 19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2169 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2173 // A final node has sent us either an invalid code or an error_code that
2174 // MUST be sent from the processing node, or the formmat of failuremsg
2175 // does not coform to the spec.
2176 // Remove it from the network map and don't may retry payment
2177 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2178 node_id: route_hop.pubkey,
2184 res = Some((None, payment_retryable));
2188 // now, error_code should be only from the intermediate nodes
2190 _c if error_code & PERM == PERM => {
2191 res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2192 short_channel_id: route_hop.short_channel_id,
2196 _c if error_code & UPDATE == UPDATE => {
2197 let offset = match error_code {
2198 c if c == UPDATE|7 => 0, // temporary_channel_failure
2199 c if c == UPDATE|11 => 8, // amount_below_minimum
2200 c if c == UPDATE|12 => 8, // fee_insufficient
2201 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2202 c if c == UPDATE|14 => 0, // expiry_too_soon
2203 c if c == UPDATE|20 => 2, // channel_disabled
2205 // node sending unknown code
2206 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2207 node_id: route_hop.pubkey,
2214 if err_packet.failuremsg.len() >= offset + 2 {
2215 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2216 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2217 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2218 // if channel_update should NOT have caused the failure:
2219 // MAY treat the channel_update as invalid.
2220 let is_chan_update_invalid = match error_code {
2221 c if c == UPDATE|7 => { // temporary_channel_failure
2224 c if c == UPDATE|11 => { // amount_below_minimum
2225 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2226 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2227 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2229 c if c == UPDATE|12 => { // fee_insufficient
2230 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2231 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) });
2232 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2233 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2235 c if c == UPDATE|13 => { // incorrect_cltv_expiry
2236 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2237 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2238 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2240 c if c == UPDATE|20 => { // channel_disabled
2241 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2242 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2243 chan_update.contents.flags & 0x01 == 0x01
2245 c if c == UPDATE|21 => true, // expiry_too_far
2246 _ => { unreachable!(); },
2249 let msg = if is_chan_update_invalid { None } else {
2250 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2254 res = Some((msg, true));
2260 _c if error_code & BADONION == BADONION => {
2263 14 => { // expiry_too_soon
2264 res = Some((None, true));
2268 // node sending unknown code
2269 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2270 node_id: route_hop.pubkey,
2279 }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2280 res.unwrap_or((None, true))
2281 } else { ((None, true)) }
2284 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2285 let mut channel_lock = self.channel_state.lock().unwrap();
2286 let channel_state = channel_lock.borrow_parts();
2287 match channel_state.by_id.entry(msg.channel_id) {
2288 hash_map::Entry::Occupied(mut chan) => {
2289 if chan.get().get_their_node_id() != *their_node_id {
2290 //TODO: here and below MsgHandleErrInternal, #153 case
2291 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2293 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2295 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2300 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2301 let mut channel_lock = self.channel_state.lock().unwrap();
2302 let channel_state = channel_lock.borrow_parts();
2303 match channel_state.by_id.entry(msg.channel_id) {
2304 hash_map::Entry::Occupied(mut chan) => {
2305 if chan.get().get_their_node_id() != *their_node_id {
2306 //TODO: here and below MsgHandleErrInternal, #153 case
2307 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2309 if (msg.failure_code & 0x8000) == 0 {
2310 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2312 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }), channel_state, chan);
2315 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2319 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2320 let mut channel_state_lock = self.channel_state.lock().unwrap();
2321 let channel_state = channel_state_lock.borrow_parts();
2322 match channel_state.by_id.entry(msg.channel_id) {
2323 hash_map::Entry::Occupied(mut chan) => {
2324 if chan.get().get_their_node_id() != *their_node_id {
2325 //TODO: here and below MsgHandleErrInternal, #153 case
2326 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2328 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2329 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2330 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2331 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2332 //TODO: Rebroadcast closing_signed if present on monitor update restoration
2334 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2335 node_id: their_node_id.clone(),
2336 msg: revoke_and_ack,
2338 if let Some(msg) = commitment_signed {
2339 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2340 node_id: their_node_id.clone(),
2341 updates: msgs::CommitmentUpdate {
2342 update_add_htlcs: Vec::new(),
2343 update_fulfill_htlcs: Vec::new(),
2344 update_fail_htlcs: Vec::new(),
2345 update_fail_malformed_htlcs: Vec::new(),
2347 commitment_signed: msg,
2351 if let Some(msg) = closing_signed {
2352 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2353 node_id: their_node_id.clone(),
2359 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2364 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2365 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2366 let mut forward_event = None;
2367 if !pending_forwards.is_empty() {
2368 let mut channel_state = self.channel_state.lock().unwrap();
2369 if channel_state.forward_htlcs.is_empty() {
2370 forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
2371 channel_state.next_forward = forward_event.unwrap();
2373 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2374 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2375 hash_map::Entry::Occupied(mut entry) => {
2376 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2378 hash_map::Entry::Vacant(entry) => {
2379 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2384 match forward_event {
2386 let mut pending_events = self.pending_events.lock().unwrap();
2387 pending_events.push(events::Event::PendingHTLCsForwardable {
2388 time_forwardable: time
2396 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2397 let (pending_forwards, mut pending_failures, short_channel_id) = {
2398 let mut channel_state_lock = self.channel_state.lock().unwrap();
2399 let channel_state = channel_state_lock.borrow_parts();
2400 match channel_state.by_id.entry(msg.channel_id) {
2401 hash_map::Entry::Occupied(mut chan) => {
2402 if chan.get().get_their_node_id() != *their_node_id {
2403 //TODO: here and below MsgHandleErrInternal, #153 case
2404 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2406 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2407 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2408 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2409 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2411 if let Some(updates) = commitment_update {
2412 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2413 node_id: their_node_id.clone(),
2417 if let Some(msg) = closing_signed {
2418 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2419 node_id: their_node_id.clone(),
2423 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2425 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2428 for failure in pending_failures.drain(..) {
2429 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2431 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2436 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2437 let mut channel_lock = self.channel_state.lock().unwrap();
2438 let channel_state = channel_lock.borrow_parts();
2439 match channel_state.by_id.entry(msg.channel_id) {
2440 hash_map::Entry::Occupied(mut chan) => {
2441 if chan.get().get_their_node_id() != *their_node_id {
2442 //TODO: here and below MsgHandleErrInternal, #153 case
2443 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2445 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2447 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2452 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2453 let mut channel_state_lock = self.channel_state.lock().unwrap();
2454 let channel_state = channel_state_lock.borrow_parts();
2456 match channel_state.by_id.entry(msg.channel_id) {
2457 hash_map::Entry::Occupied(mut chan) => {
2458 if chan.get().get_their_node_id() != *their_node_id {
2459 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2461 if !chan.get().is_usable() {
2462 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2465 let our_node_id = self.get_our_node_id();
2466 let (announcement, our_bitcoin_sig) =
2467 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2469 let were_node_one = announcement.node_id_1 == our_node_id;
2470 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2471 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2472 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2473 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2476 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2478 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2479 msg: msgs::ChannelAnnouncement {
2480 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2481 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2482 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2483 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2484 contents: announcement,
2486 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2489 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2494 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2495 let mut channel_state_lock = self.channel_state.lock().unwrap();
2496 let channel_state = channel_state_lock.borrow_parts();
2498 match channel_state.by_id.entry(msg.channel_id) {
2499 hash_map::Entry::Occupied(mut chan) => {
2500 if chan.get().get_their_node_id() != *their_node_id {
2501 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2503 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2504 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2505 if let Some(monitor) = channel_monitor {
2506 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2507 // channel_reestablish doesn't guarantee the order it returns is sensical
2508 // for the messages it returns, but if we're setting what messages to
2509 // re-transmit on monitor update success, we need to make sure it is sane.
2510 if revoke_and_ack.is_none() {
2511 order = RAACommitmentOrder::CommitmentFirst;
2513 if commitment_update.is_none() {
2514 order = RAACommitmentOrder::RevokeAndACKFirst;
2516 return_monitor_err!(self, e, channel_state, chan, order);
2517 //TODO: Resend the funding_locked if needed once we get the monitor running again
2520 if let Some(msg) = funding_locked {
2521 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2522 node_id: their_node_id.clone(),
2526 macro_rules! send_raa { () => {
2527 if let Some(msg) = revoke_and_ack {
2528 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2529 node_id: their_node_id.clone(),
2534 macro_rules! send_cu { () => {
2535 if let Some(updates) = commitment_update {
2536 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2537 node_id: their_node_id.clone(),
2543 RAACommitmentOrder::RevokeAndACKFirst => {
2547 RAACommitmentOrder::CommitmentFirst => {
2552 if let Some(msg) = shutdown {
2553 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2554 node_id: their_node_id.clone(),
2560 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2564 /// Begin Update fee process. Allowed only on an outbound channel.
2565 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2566 /// PeerManager::process_events afterwards.
2567 /// Note: This API is likely to change!
2569 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2570 let _ = self.total_consistency_lock.read().unwrap();
2572 let err: Result<(), _> = loop {
2573 let mut channel_state_lock = self.channel_state.lock().unwrap();
2574 let channel_state = channel_state_lock.borrow_parts();
2576 match channel_state.by_id.entry(channel_id) {
2577 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2578 hash_map::Entry::Occupied(mut chan) => {
2579 if !chan.get().is_outbound() {
2580 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2582 if chan.get().is_awaiting_monitor_update() {
2583 return Err(APIError::MonitorUpdateFailed);
2585 if !chan.get().is_live() {
2586 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2588 their_node_id = chan.get().get_their_node_id();
2589 if let Some((update_fee, commitment_signed, chan_monitor)) =
2590 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2592 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2595 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2596 node_id: chan.get().get_their_node_id(),
2597 updates: msgs::CommitmentUpdate {
2598 update_add_htlcs: Vec::new(),
2599 update_fulfill_htlcs: Vec::new(),
2600 update_fail_htlcs: Vec::new(),
2601 update_fail_malformed_htlcs: Vec::new(),
2602 update_fee: Some(update_fee),
2612 match handle_error!(self, err, their_node_id) {
2613 Ok(_) => unreachable!(),
2615 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2617 log_error!(self, "Got bad keys: {}!", e.err);
2618 let mut channel_state = self.channel_state.lock().unwrap();
2619 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2620 node_id: their_node_id,
2624 Err(APIError::APIMisuseError { err: e.err })
2630 impl events::MessageSendEventsProvider for ChannelManager {
2631 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2632 let mut ret = Vec::new();
2633 let mut channel_state = self.channel_state.lock().unwrap();
2634 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2639 impl events::EventsProvider for ChannelManager {
2640 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2641 let mut ret = Vec::new();
2642 let mut pending_events = self.pending_events.lock().unwrap();
2643 mem::swap(&mut ret, &mut *pending_events);
2648 impl ChainListener for ChannelManager {
2649 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2650 let _ = self.total_consistency_lock.read().unwrap();
2651 let mut failed_channels = Vec::new();
2653 let mut channel_lock = self.channel_state.lock().unwrap();
2654 let channel_state = channel_lock.borrow_parts();
2655 let short_to_id = channel_state.short_to_id;
2656 let pending_msg_events = channel_state.pending_msg_events;
2657 channel_state.by_id.retain(|_, channel| {
2658 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2659 if let Ok(Some(funding_locked)) = chan_res {
2660 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2661 node_id: channel.get_their_node_id(),
2662 msg: funding_locked,
2664 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2665 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2666 node_id: channel.get_their_node_id(),
2667 msg: announcement_sigs,
2670 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2671 } else if let Err(e) = chan_res {
2672 pending_msg_events.push(events::MessageSendEvent::HandleError {
2673 node_id: channel.get_their_node_id(),
2674 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2678 if let Some(funding_txo) = channel.get_funding_txo() {
2679 for tx in txn_matched {
2680 for inp in tx.input.iter() {
2681 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2682 if let Some(short_id) = channel.get_short_channel_id() {
2683 short_to_id.remove(&short_id);
2685 // It looks like our counterparty went on-chain. We go ahead and
2686 // broadcast our latest local state as well here, just in case its
2687 // some kind of SPV attack, though we expect these to be dropped.
2688 failed_channels.push(channel.force_shutdown());
2689 if let Ok(update) = self.get_channel_update(&channel) {
2690 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2699 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2700 if let Some(short_id) = channel.get_short_channel_id() {
2701 short_to_id.remove(&short_id);
2703 failed_channels.push(channel.force_shutdown());
2704 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2705 // the latest local tx for us, so we should skip that here (it doesn't really
2706 // hurt anything, but does make tests a bit simpler).
2707 failed_channels.last_mut().unwrap().0 = Vec::new();
2708 if let Ok(update) = self.get_channel_update(&channel) {
2709 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2718 for failure in failed_channels.drain(..) {
2719 self.finish_force_close_channel(failure);
2721 self.latest_block_height.store(height as usize, Ordering::Release);
2722 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2725 /// We force-close the channel without letting our counterparty participate in the shutdown
2726 fn block_disconnected(&self, header: &BlockHeader) {
2727 let _ = self.total_consistency_lock.read().unwrap();
2728 let mut failed_channels = Vec::new();
2730 let mut channel_lock = self.channel_state.lock().unwrap();
2731 let channel_state = channel_lock.borrow_parts();
2732 let short_to_id = channel_state.short_to_id;
2733 let pending_msg_events = channel_state.pending_msg_events;
2734 channel_state.by_id.retain(|_, v| {
2735 if v.block_disconnected(header) {
2736 if let Some(short_id) = v.get_short_channel_id() {
2737 short_to_id.remove(&short_id);
2739 failed_channels.push(v.force_shutdown());
2740 if let Ok(update) = self.get_channel_update(&v) {
2741 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2751 for failure in failed_channels.drain(..) {
2752 self.finish_force_close_channel(failure);
2754 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2755 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2759 impl ChannelMessageHandler for ChannelManager {
2760 //TODO: Handle errors and close channel (or so)
2761 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2762 let _ = self.total_consistency_lock.read().unwrap();
2763 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2766 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2767 let _ = self.total_consistency_lock.read().unwrap();
2768 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2771 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2772 let _ = self.total_consistency_lock.read().unwrap();
2773 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2776 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2777 let _ = self.total_consistency_lock.read().unwrap();
2778 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2781 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2782 let _ = self.total_consistency_lock.read().unwrap();
2783 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2786 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2787 let _ = self.total_consistency_lock.read().unwrap();
2788 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2791 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2792 let _ = self.total_consistency_lock.read().unwrap();
2793 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2796 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2797 let _ = self.total_consistency_lock.read().unwrap();
2798 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2801 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2802 let _ = self.total_consistency_lock.read().unwrap();
2803 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2806 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2807 let _ = self.total_consistency_lock.read().unwrap();
2808 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2811 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2812 let _ = self.total_consistency_lock.read().unwrap();
2813 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2816 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2817 let _ = self.total_consistency_lock.read().unwrap();
2818 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2821 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2822 let _ = self.total_consistency_lock.read().unwrap();
2823 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2826 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2827 let _ = self.total_consistency_lock.read().unwrap();
2828 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2831 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2832 let _ = self.total_consistency_lock.read().unwrap();
2833 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2836 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2837 let _ = self.total_consistency_lock.read().unwrap();
2838 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2841 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2842 let _ = self.total_consistency_lock.read().unwrap();
2843 let mut failed_channels = Vec::new();
2844 let mut failed_payments = Vec::new();
2846 let mut channel_state_lock = self.channel_state.lock().unwrap();
2847 let channel_state = channel_state_lock.borrow_parts();
2848 let short_to_id = channel_state.short_to_id;
2849 let pending_msg_events = channel_state.pending_msg_events;
2850 if no_connection_possible {
2851 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2852 channel_state.by_id.retain(|_, chan| {
2853 if chan.get_their_node_id() == *their_node_id {
2854 if let Some(short_id) = chan.get_short_channel_id() {
2855 short_to_id.remove(&short_id);
2857 failed_channels.push(chan.force_shutdown());
2858 if let Ok(update) = self.get_channel_update(&chan) {
2859 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2869 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2870 channel_state.by_id.retain(|_, chan| {
2871 if chan.get_their_node_id() == *their_node_id {
2872 //TODO: mark channel disabled (and maybe announce such after a timeout).
2873 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2874 if !failed_adds.is_empty() {
2875 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
2876 failed_payments.push((chan_update, failed_adds));
2878 if chan.is_shutdown() {
2879 if let Some(short_id) = chan.get_short_channel_id() {
2880 short_to_id.remove(&short_id);
2889 for failure in failed_channels.drain(..) {
2890 self.finish_force_close_channel(failure);
2892 for (chan_update, mut htlc_sources) in failed_payments {
2893 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2894 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2899 fn peer_connected(&self, their_node_id: &PublicKey) {
2900 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2902 let _ = self.total_consistency_lock.read().unwrap();
2903 let mut channel_state_lock = self.channel_state.lock().unwrap();
2904 let channel_state = channel_state_lock.borrow_parts();
2905 let pending_msg_events = channel_state.pending_msg_events;
2906 channel_state.by_id.retain(|_, chan| {
2907 if chan.get_their_node_id() == *their_node_id {
2908 if !chan.have_received_message() {
2909 // If we created this (outbound) channel while we were disconnected from the
2910 // peer we probably failed to send the open_channel message, which is now
2911 // lost. We can't have had anything pending related to this channel, so we just
2915 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2916 node_id: chan.get_their_node_id(),
2917 msg: chan.get_channel_reestablish(),
2923 //TODO: Also re-broadcast announcement_signatures
2926 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2927 let _ = self.total_consistency_lock.read().unwrap();
2929 if msg.channel_id == [0; 32] {
2930 for chan in self.list_channels() {
2931 if chan.remote_network_id == *their_node_id {
2932 self.force_close_channel(&chan.channel_id);
2936 self.force_close_channel(&msg.channel_id);
2941 const SERIALIZATION_VERSION: u8 = 1;
2942 const MIN_SERIALIZATION_VERSION: u8 = 1;
2944 impl Writeable for PendingForwardHTLCInfo {
2945 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2946 if let &Some(ref onion) = &self.onion_packet {
2948 onion.write(writer)?;
2952 self.incoming_shared_secret.write(writer)?;
2953 self.payment_hash.write(writer)?;
2954 self.short_channel_id.write(writer)?;
2955 self.amt_to_forward.write(writer)?;
2956 self.outgoing_cltv_value.write(writer)?;
2961 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2962 fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2963 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2965 1 => Some(msgs::OnionPacket::read(reader)?),
2966 _ => return Err(DecodeError::InvalidValue),
2968 Ok(PendingForwardHTLCInfo {
2970 incoming_shared_secret: Readable::read(reader)?,
2971 payment_hash: Readable::read(reader)?,
2972 short_channel_id: Readable::read(reader)?,
2973 amt_to_forward: Readable::read(reader)?,
2974 outgoing_cltv_value: Readable::read(reader)?,
2979 impl Writeable for HTLCFailureMsg {
2980 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2982 &HTLCFailureMsg::Relay(ref fail_msg) => {
2984 fail_msg.write(writer)?;
2986 &HTLCFailureMsg::Malformed(ref fail_msg) => {
2988 fail_msg.write(writer)?;
2995 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
2996 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
2997 match <u8 as Readable<R>>::read(reader)? {
2998 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
2999 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3000 _ => Err(DecodeError::InvalidValue),
3005 impl Writeable for PendingHTLCStatus {
3006 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3008 &PendingHTLCStatus::Forward(ref forward_info) => {
3010 forward_info.write(writer)?;
3012 &PendingHTLCStatus::Fail(ref fail_msg) => {
3014 fail_msg.write(writer)?;
3021 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3022 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3023 match <u8 as Readable<R>>::read(reader)? {
3024 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3025 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3026 _ => Err(DecodeError::InvalidValue),
3031 impl_writeable!(HTLCPreviousHopData, 0, {
3034 incoming_packet_shared_secret
3037 impl Writeable for HTLCSource {
3038 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3040 &HTLCSource::PreviousHopData(ref hop_data) => {
3042 hop_data.write(writer)?;
3044 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3046 route.write(writer)?;
3047 session_priv.write(writer)?;
3048 first_hop_htlc_msat.write(writer)?;
3055 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3056 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3057 match <u8 as Readable<R>>::read(reader)? {
3058 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3059 1 => Ok(HTLCSource::OutboundRoute {
3060 route: Readable::read(reader)?,
3061 session_priv: Readable::read(reader)?,
3062 first_hop_htlc_msat: Readable::read(reader)?,
3064 _ => Err(DecodeError::InvalidValue),
3069 impl Writeable for HTLCFailReason {
3070 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3072 &HTLCFailReason::ErrorPacket { ref err } => {
3076 &HTLCFailReason::Reason { ref failure_code, ref data } => {
3078 failure_code.write(writer)?;
3079 data.write(writer)?;
3086 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3087 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3088 match <u8 as Readable<R>>::read(reader)? {
3089 0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3090 1 => Ok(HTLCFailReason::Reason {
3091 failure_code: Readable::read(reader)?,
3092 data: Readable::read(reader)?,
3094 _ => Err(DecodeError::InvalidValue),
3099 impl_writeable!(HTLCForwardInfo, 0, {
3100 prev_short_channel_id,
3105 impl Writeable for ChannelManager {
3106 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3107 let _ = self.total_consistency_lock.write().unwrap();
3109 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3110 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3112 self.genesis_hash.write(writer)?;
3113 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3114 self.last_block_hash.lock().unwrap().write(writer)?;
3116 let channel_state = self.channel_state.lock().unwrap();
3117 let mut unfunded_channels = 0;
3118 for (_, channel) in channel_state.by_id.iter() {
3119 if !channel.is_funding_initiated() {
3120 unfunded_channels += 1;
3123 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3124 for (_, channel) in channel_state.by_id.iter() {
3125 if channel.is_funding_initiated() {
3126 channel.write(writer)?;
3130 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3131 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3132 short_channel_id.write(writer)?;
3133 (pending_forwards.len() as u64).write(writer)?;
3134 for forward in pending_forwards {
3135 forward.write(writer)?;
3139 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3140 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3141 payment_hash.write(writer)?;
3142 (previous_hops.len() as u64).write(writer)?;
3143 for previous_hop in previous_hops {
3144 previous_hop.write(writer)?;
3152 /// Arguments for the creation of a ChannelManager that are not deserialized.
3154 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3156 /// 1) Deserialize all stored ChannelMonitors.
3157 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3158 /// ChannelManager)>::read(reader, args).
3159 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
3160 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3161 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3162 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3163 /// 4) Reconnect blocks on your ChannelMonitors.
3164 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3165 /// 6) Disconnect/connect blocks on the ChannelManager.
3166 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3167 /// automatically as it does in ChannelManager::new()).
3168 pub struct ChannelManagerReadArgs<'a> {
3169 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3170 /// deserialization.
3171 pub keys_manager: Arc<KeysInterface>,
3173 /// The fee_estimator for use in the ChannelManager in the future.
3175 /// No calls to the FeeEstimator will be made during deserialization.
3176 pub fee_estimator: Arc<FeeEstimator>,
3177 /// The ManyChannelMonitor for use in the ChannelManager in the future.
3179 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3180 /// you have deserialized ChannelMonitors separately and will add them to your
3181 /// ManyChannelMonitor after deserializing this ChannelManager.
3182 pub monitor: Arc<ManyChannelMonitor>,
3183 /// The ChainWatchInterface for use in the ChannelManager in the future.
3185 /// No calls to the ChainWatchInterface will be made during deserialization.
3186 pub chain_monitor: Arc<ChainWatchInterface>,
3187 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3188 /// used to broadcast the latest local commitment transactions of channels which must be
3189 /// force-closed during deserialization.
3190 pub tx_broadcaster: Arc<BroadcasterInterface>,
3191 /// The Logger for use in the ChannelManager and which may be used to log information during
3192 /// deserialization.
3193 pub logger: Arc<Logger>,
3194 /// Default settings used for new channels. Any existing channels will continue to use the
3195 /// runtime settings which were stored when the ChannelManager was serialized.
3196 pub default_config: UserConfig,
3198 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3199 /// value.get_funding_txo() should be the key).
3201 /// If a monitor is inconsistent with the channel state during deserialization the channel will
3202 /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3203 /// is true for missing channels as well. If there is a monitor missing for which we find
3204 /// channel data Err(DecodeError::InvalidValue) will be returned.
3206 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3208 pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3211 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3212 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3213 let _ver: u8 = Readable::read(reader)?;
3214 let min_ver: u8 = Readable::read(reader)?;
3215 if min_ver > SERIALIZATION_VERSION {
3216 return Err(DecodeError::UnknownVersion);
3219 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3220 let latest_block_height: u32 = Readable::read(reader)?;
3221 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3223 let mut closed_channels = Vec::new();
3225 let channel_count: u64 = Readable::read(reader)?;
3226 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3227 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3228 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3229 for _ in 0..channel_count {
3230 let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3231 if channel.last_block_connected != last_block_hash {
3232 return Err(DecodeError::InvalidValue);
3235 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3236 funding_txo_set.insert(funding_txo.clone());
3237 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3238 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3239 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3240 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3241 let mut force_close_res = channel.force_shutdown();
3242 force_close_res.0 = monitor.get_latest_local_commitment_txn();
3243 closed_channels.push(force_close_res);
3245 if let Some(short_channel_id) = channel.get_short_channel_id() {
3246 short_to_id.insert(short_channel_id, channel.channel_id());
3248 by_id.insert(channel.channel_id(), channel);
3251 return Err(DecodeError::InvalidValue);
3255 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3256 if !funding_txo_set.contains(funding_txo) {
3257 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3261 let forward_htlcs_count: u64 = Readable::read(reader)?;
3262 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3263 for _ in 0..forward_htlcs_count {
3264 let short_channel_id = Readable::read(reader)?;
3265 let pending_forwards_count: u64 = Readable::read(reader)?;
3266 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3267 for _ in 0..pending_forwards_count {
3268 pending_forwards.push(Readable::read(reader)?);
3270 forward_htlcs.insert(short_channel_id, pending_forwards);
3273 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3274 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3275 for _ in 0..claimable_htlcs_count {
3276 let payment_hash = Readable::read(reader)?;
3277 let previous_hops_len: u64 = Readable::read(reader)?;
3278 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3279 for _ in 0..previous_hops_len {
3280 previous_hops.push(Readable::read(reader)?);
3282 claimable_htlcs.insert(payment_hash, previous_hops);
3285 let channel_manager = ChannelManager {
3287 fee_estimator: args.fee_estimator,
3288 monitor: args.monitor,
3289 chain_monitor: args.chain_monitor,
3290 tx_broadcaster: args.tx_broadcaster,
3292 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3293 last_block_hash: Mutex::new(last_block_hash),
3294 secp_ctx: Secp256k1::new(),
3296 channel_state: Mutex::new(ChannelHolder {
3299 next_forward: Instant::now(),
3302 pending_msg_events: Vec::new(),
3304 our_network_key: args.keys_manager.get_node_secret(),
3306 pending_events: Mutex::new(Vec::new()),
3307 total_consistency_lock: RwLock::new(()),
3308 keys_manager: args.keys_manager,
3309 logger: args.logger,
3310 default_configuration: args.default_config,
3313 for close_res in closed_channels.drain(..) {
3314 channel_manager.finish_force_close_channel(close_res);
3315 //TODO: Broadcast channel update for closed channels, but only after we've made a
3316 //connection or two.
3319 Ok((last_block_hash.clone(), channel_manager))
3325 use chain::chaininterface;
3326 use chain::transaction::OutPoint;
3327 use chain::chaininterface::{ChainListener, ChainWatchInterface};
3328 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3329 use chain::keysinterface;
3330 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3331 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder};
3332 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3333 use ln::router::{Route, RouteHop, Router};
3335 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3336 use util::test_utils;
3337 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3338 use util::errors::APIError;
3339 use util::logger::Logger;
3340 use util::ser::{Writeable, Writer, ReadableArgs};
3341 use util::config::UserConfig;
3343 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3344 use bitcoin::util::bip143;
3345 use bitcoin::util::address::Address;
3346 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3347 use bitcoin::blockdata::block::{Block, BlockHeader};
3348 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3349 use bitcoin::blockdata::script::{Builder, Script};
3350 use bitcoin::blockdata::opcodes;
3351 use bitcoin::blockdata::constants::genesis_block;
3352 use bitcoin::network::constants::Network;
3356 use secp256k1::{Secp256k1, Message};
3357 use secp256k1::key::{PublicKey,SecretKey};
3359 use crypto::sha2::Sha256;
3360 use crypto::digest::Digest;
3362 use rand::{thread_rng,Rng};
3364 use std::cell::RefCell;
3365 use std::collections::{BTreeSet, HashMap};
3366 use std::default::Default;
3368 use std::sync::{Arc, Mutex};
3369 use std::sync::atomic::Ordering;
3370 use std::time::Instant;
3373 fn build_test_onion_keys() -> Vec<OnionKeys> {
3374 // Keys from BOLT 4, used in both test vector tests
3375 let secp_ctx = Secp256k1::new();
3380 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3381 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
3384 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3385 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
3388 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3389 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
3392 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3393 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
3396 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3397 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
3402 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3404 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3405 assert_eq!(onion_keys.len(), route.hops.len());
3410 fn onion_vectors() {
3411 // Packet creation test vectors from BOLT 4
3412 let onion_keys = build_test_onion_keys();
3414 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3415 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3416 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3417 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3418 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3420 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3421 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3422 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3423 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3424 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3426 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3427 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3428 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3429 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3430 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3432 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3433 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3434 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3435 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3436 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3438 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3439 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3440 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3441 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3442 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3444 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3445 let payloads = vec!(
3446 msgs::OnionHopData {
3448 data: msgs::OnionRealm0HopData {
3449 short_channel_id: 0,
3451 outgoing_cltv_value: 0,
3455 msgs::OnionHopData {
3457 data: msgs::OnionRealm0HopData {
3458 short_channel_id: 0x0101010101010101,
3459 amt_to_forward: 0x0100000001,
3460 outgoing_cltv_value: 0,
3464 msgs::OnionHopData {
3466 data: msgs::OnionRealm0HopData {
3467 short_channel_id: 0x0202020202020202,
3468 amt_to_forward: 0x0200000002,
3469 outgoing_cltv_value: 0,
3473 msgs::OnionHopData {
3475 data: msgs::OnionRealm0HopData {
3476 short_channel_id: 0x0303030303030303,
3477 amt_to_forward: 0x0300000003,
3478 outgoing_cltv_value: 0,
3482 msgs::OnionHopData {
3484 data: msgs::OnionRealm0HopData {
3485 short_channel_id: 0x0404040404040404,
3486 amt_to_forward: 0x0400000004,
3487 outgoing_cltv_value: 0,
3493 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
3494 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3496 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3500 fn test_failure_packet_onion() {
3501 // Returning Errors test vectors from BOLT 4
3503 let onion_keys = build_test_onion_keys();
3504 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3505 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3507 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3508 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3510 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3511 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3513 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3514 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3516 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3517 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3519 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3520 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3523 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3524 assert!(chain.does_match_tx(tx));
3525 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3526 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3528 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3529 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3534 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3535 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3536 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3537 node: Arc<ChannelManager>,
3539 node_seed: [u8; 32],
3540 network_payment_count: Rc<RefCell<u8>>,
3541 network_chan_count: Rc<RefCell<u32>>,
3543 impl Drop for Node {
3544 fn drop(&mut self) {
3545 if !::std::thread::panicking() {
3546 // Check that we processed all pending events
3547 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3548 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3549 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3554 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3555 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3558 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) {
3559 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3560 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3561 (announcement, as_update, bs_update, channel_id, tx)
3564 macro_rules! get_revoke_commit_msgs {
3565 ($node: expr, $node_id: expr) => {
3567 let events = $node.node.get_and_clear_pending_msg_events();
3568 assert_eq!(events.len(), 2);
3570 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3571 assert_eq!(*node_id, $node_id);
3574 _ => panic!("Unexpected event"),
3575 }, match events[1] {
3576 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3577 assert_eq!(*node_id, $node_id);
3578 assert!(updates.update_add_htlcs.is_empty());
3579 assert!(updates.update_fulfill_htlcs.is_empty());
3580 assert!(updates.update_fail_htlcs.is_empty());
3581 assert!(updates.update_fail_malformed_htlcs.is_empty());
3582 assert!(updates.update_fee.is_none());
3583 updates.commitment_signed.clone()
3585 _ => panic!("Unexpected event"),
3591 macro_rules! get_event_msg {
3592 ($node: expr, $event_type: path, $node_id: expr) => {
3594 let events = $node.node.get_and_clear_pending_msg_events();
3595 assert_eq!(events.len(), 1);
3597 $event_type { ref node_id, ref msg } => {
3598 assert_eq!(*node_id, $node_id);
3601 _ => panic!("Unexpected event"),
3607 macro_rules! get_htlc_update_msgs {
3608 ($node: expr, $node_id: expr) => {
3610 let events = $node.node.get_and_clear_pending_msg_events();
3611 assert_eq!(events.len(), 1);
3613 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3614 assert_eq!(*node_id, $node_id);
3617 _ => panic!("Unexpected event"),
3623 macro_rules! get_feerate {
3624 ($node: expr, $channel_id: expr) => {
3626 let chan_lock = $node.node.channel_state.lock().unwrap();
3627 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3634 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3635 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3636 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();
3637 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();
3639 let chan_id = *node_a.network_chan_count.borrow();
3643 let events_2 = node_a.node.get_and_clear_pending_events();
3644 assert_eq!(events_2.len(), 1);
3646 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3647 assert_eq!(*channel_value_satoshis, channel_value);
3648 assert_eq!(user_channel_id, 42);
3650 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3651 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3653 funding_output = OutPoint::new(tx.txid(), 0);
3655 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3656 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3657 assert_eq!(added_monitors.len(), 1);
3658 assert_eq!(added_monitors[0].0, funding_output);
3659 added_monitors.clear();
3661 _ => panic!("Unexpected event"),
3664 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();
3666 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3667 assert_eq!(added_monitors.len(), 1);
3668 assert_eq!(added_monitors[0].0, funding_output);
3669 added_monitors.clear();
3672 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();
3674 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3675 assert_eq!(added_monitors.len(), 1);
3676 assert_eq!(added_monitors[0].0, funding_output);
3677 added_monitors.clear();
3680 let events_4 = node_a.node.get_and_clear_pending_events();
3681 assert_eq!(events_4.len(), 1);
3683 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3684 assert_eq!(user_channel_id, 42);
3685 assert_eq!(*funding_txo, funding_output);
3687 _ => panic!("Unexpected event"),
3693 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3694 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3695 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();
3699 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3700 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3701 assert_eq!(events_6.len(), 2);
3702 ((match events_6[0] {
3703 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3704 channel_id = msg.channel_id.clone();
3705 assert_eq!(*node_id, node_b.node.get_our_node_id());
3708 _ => panic!("Unexpected event"),
3709 }, match events_6[1] {
3710 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3711 assert_eq!(*node_id, node_b.node.get_our_node_id());
3714 _ => panic!("Unexpected event"),
3718 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) {
3719 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3720 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3724 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) {
3725 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3726 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3727 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3729 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3730 assert_eq!(events_7.len(), 1);
3731 let (announcement, bs_update) = match events_7[0] {
3732 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3735 _ => panic!("Unexpected event"),
3738 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3739 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3740 assert_eq!(events_8.len(), 1);
3741 let as_update = match events_8[0] {
3742 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3743 assert!(*announcement == *msg);
3746 _ => panic!("Unexpected event"),
3749 *node_a.network_chan_count.borrow_mut() += 1;
3751 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3754 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3755 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3758 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) {
3759 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3761 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3762 node.router.handle_channel_update(&chan_announcement.1).unwrap();
3763 node.router.handle_channel_update(&chan_announcement.2).unwrap();
3765 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3768 macro_rules! check_spends {
3769 ($tx: expr, $spends_tx: expr) => {
3771 let mut funding_tx_map = HashMap::new();
3772 let spends_tx = $spends_tx;
3773 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3774 $tx.verify(&funding_tx_map).unwrap();
3779 macro_rules! get_closing_signed_broadcast {
3780 ($node: expr, $dest_pubkey: expr) => {
3782 let events = $node.get_and_clear_pending_msg_events();
3783 assert!(events.len() == 1 || events.len() == 2);
3784 (match events[events.len() - 1] {
3785 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3786 assert_eq!(msg.contents.flags & 2, 2);
3789 _ => panic!("Unexpected event"),
3790 }, if events.len() == 2 {
3792 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3793 assert_eq!(*node_id, $dest_pubkey);
3796 _ => panic!("Unexpected event"),
3803 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) {
3804 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) };
3805 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3808 node_a.close_channel(channel_id).unwrap();
3809 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3811 let events_1 = node_b.get_and_clear_pending_msg_events();
3812 assert!(events_1.len() >= 1);
3813 let shutdown_b = match events_1[0] {
3814 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3815 assert_eq!(node_id, &node_a.get_our_node_id());
3818 _ => panic!("Unexpected event"),
3821 let closing_signed_b = if !close_inbound_first {
3822 assert_eq!(events_1.len(), 1);
3825 Some(match events_1[1] {
3826 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3827 assert_eq!(node_id, &node_a.get_our_node_id());
3830 _ => panic!("Unexpected event"),
3834 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3835 let (as_update, bs_update) = if close_inbound_first {
3836 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3837 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3838 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3839 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3840 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3842 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3843 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3844 assert!(none_b.is_none());
3845 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3846 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3847 (as_update, bs_update)
3849 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3851 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3852 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3853 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3854 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3856 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3857 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3858 assert!(none_a.is_none());
3859 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3860 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3861 (as_update, bs_update)
3863 assert_eq!(tx_a, tx_b);
3864 check_spends!(tx_a, funding_tx);
3866 (as_update, bs_update, tx_a)
3871 msgs: Vec<msgs::UpdateAddHTLC>,
3872 commitment_msg: msgs::CommitmentSigned,
3875 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3876 assert!(updates.update_fulfill_htlcs.is_empty());
3877 assert!(updates.update_fail_htlcs.is_empty());
3878 assert!(updates.update_fail_malformed_htlcs.is_empty());
3879 assert!(updates.update_fee.is_none());
3880 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3883 fn from_event(event: MessageSendEvent) -> SendEvent {
3885 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3886 _ => panic!("Unexpected event type!"),
3891 macro_rules! check_added_monitors {
3892 ($node: expr, $count: expr) => {
3894 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3895 assert_eq!(added_monitors.len(), $count);
3896 added_monitors.clear();
3901 macro_rules! commitment_signed_dance {
3902 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3904 check_added_monitors!($node_a, 0);
3905 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3906 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3907 check_added_monitors!($node_a, 1);
3908 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3911 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3913 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3914 check_added_monitors!($node_b, 0);
3915 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3916 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3917 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3918 check_added_monitors!($node_b, 1);
3919 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3920 let (bs_revoke_and_ack, extra_msg_option) = {
3921 let events = $node_b.node.get_and_clear_pending_msg_events();
3922 assert!(events.len() <= 2);
3924 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3925 assert_eq!(*node_id, $node_a.node.get_our_node_id());
3928 _ => panic!("Unexpected event"),
3929 }, events.get(1).map(|e| e.clone()))
3931 check_added_monitors!($node_b, 1);
3932 if $fail_backwards {
3933 assert!($node_a.node.get_and_clear_pending_events().is_empty());
3934 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3936 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3938 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3939 if $fail_backwards {
3940 assert_eq!(added_monitors.len(), 2);
3941 assert!(added_monitors[0].0 != added_monitors[1].0);
3943 assert_eq!(added_monitors.len(), 1);
3945 added_monitors.clear();
3950 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
3952 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
3955 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3957 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
3958 if $fail_backwards {
3959 let channel_state = $node_a.node.channel_state.lock().unwrap();
3960 assert_eq!(channel_state.pending_msg_events.len(), 1);
3961 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
3962 assert_ne!(*node_id, $node_b.node.get_our_node_id());
3963 } else { panic!("Unexpected event"); }
3965 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3971 macro_rules! get_payment_preimage_hash {
3974 let payment_preimage = [*$node.network_payment_count.borrow(); 32];
3975 *$node.network_payment_count.borrow_mut() += 1;
3976 let mut payment_hash = [0; 32];
3977 let mut sha = Sha256::new();
3978 sha.input(&payment_preimage[..]);
3979 sha.result(&mut payment_hash);
3980 (payment_preimage, payment_hash)
3985 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3986 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3988 let mut payment_event = {
3989 origin_node.node.send_payment(route, our_payment_hash).unwrap();
3990 check_added_monitors!(origin_node, 1);
3992 let mut events = origin_node.node.get_and_clear_pending_msg_events();
3993 assert_eq!(events.len(), 1);
3994 SendEvent::from_event(events.remove(0))
3996 let mut prev_node = origin_node;
3998 for (idx, &node) in expected_route.iter().enumerate() {
3999 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4001 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4002 check_added_monitors!(node, 0);
4003 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4005 let events_1 = node.node.get_and_clear_pending_events();
4006 assert_eq!(events_1.len(), 1);
4008 Event::PendingHTLCsForwardable { .. } => { },
4009 _ => panic!("Unexpected event"),
4012 node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4013 node.node.process_pending_htlc_forwards();
4015 if idx == expected_route.len() - 1 {
4016 let events_2 = node.node.get_and_clear_pending_events();
4017 assert_eq!(events_2.len(), 1);
4019 Event::PaymentReceived { ref payment_hash, amt } => {
4020 assert_eq!(our_payment_hash, *payment_hash);
4021 assert_eq!(amt, recv_value);
4023 _ => panic!("Unexpected event"),
4026 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4027 assert_eq!(events_2.len(), 1);
4028 check_added_monitors!(node, 1);
4029 payment_event = SendEvent::from_event(events_2.remove(0));
4030 assert_eq!(payment_event.msgs.len(), 1);
4036 (our_payment_preimage, our_payment_hash)
4039 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
4040 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4041 check_added_monitors!(expected_route.last().unwrap(), 1);
4043 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4044 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4045 macro_rules! get_next_msgs {
4048 let events = $node.node.get_and_clear_pending_msg_events();
4049 assert_eq!(events.len(), 1);
4051 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 } } => {
4052 assert!(update_add_htlcs.is_empty());
4053 assert_eq!(update_fulfill_htlcs.len(), 1);
4054 assert!(update_fail_htlcs.is_empty());
4055 assert!(update_fail_malformed_htlcs.is_empty());
4056 assert!(update_fee.is_none());
4057 expected_next_node = node_id.clone();
4058 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4060 _ => panic!("Unexpected event"),
4066 macro_rules! last_update_fulfill_dance {
4067 ($node: expr, $prev_node: expr) => {
4069 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4070 check_added_monitors!($node, 0);
4071 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4072 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4076 macro_rules! mid_update_fulfill_dance {
4077 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4079 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4080 check_added_monitors!($node, 1);
4081 let new_next_msgs = if $new_msgs {
4082 get_next_msgs!($node)
4084 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4087 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4088 next_msgs = new_next_msgs;
4093 let mut prev_node = expected_route.last().unwrap();
4094 for (idx, node) in expected_route.iter().rev().enumerate() {
4095 assert_eq!(expected_next_node, node.node.get_our_node_id());
4096 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4097 if next_msgs.is_some() {
4098 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4099 } else if update_next_msgs {
4100 next_msgs = get_next_msgs!(node);
4102 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4104 if !skip_last && idx == expected_route.len() - 1 {
4105 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4112 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4113 let events = origin_node.node.get_and_clear_pending_events();
4114 assert_eq!(events.len(), 1);
4116 Event::PaymentSent { payment_preimage } => {
4117 assert_eq!(payment_preimage, our_payment_preimage);
4119 _ => panic!("Unexpected event"),
4124 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
4125 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4128 const TEST_FINAL_CLTV: u32 = 32;
4130 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
4131 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();
4132 assert_eq!(route.hops.len(), expected_route.len());
4133 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4134 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4137 send_along_route(origin_node, route, expected_route, recv_value)
4140 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4141 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();
4142 assert_eq!(route.hops.len(), expected_route.len());
4143 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4144 assert_eq!(hop.pubkey, node.node.get_our_node_id());
4147 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4149 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4151 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4152 _ => panic!("Unknown error variants"),
4156 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4157 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4158 claim_payment(&origin, expected_route, our_payment_preimage);
4161 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
4162 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4163 check_added_monitors!(expected_route.last().unwrap(), 1);
4165 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4166 macro_rules! update_fail_dance {
4167 ($node: expr, $prev_node: expr, $last_node: expr) => {
4169 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4170 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4175 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4176 let mut prev_node = expected_route.last().unwrap();
4177 for (idx, node) in expected_route.iter().rev().enumerate() {
4178 assert_eq!(expected_next_node, node.node.get_our_node_id());
4179 if next_msgs.is_some() {
4180 // We may be the "last node" for the purpose of the commitment dance if we're
4181 // skipping the last node (implying it is disconnected) and we're the
4182 // second-to-last node!
4183 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4186 let events = node.node.get_and_clear_pending_msg_events();
4187 if !skip_last || idx != expected_route.len() - 1 {
4188 assert_eq!(events.len(), 1);
4190 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 } } => {
4191 assert!(update_add_htlcs.is_empty());
4192 assert!(update_fulfill_htlcs.is_empty());
4193 assert_eq!(update_fail_htlcs.len(), 1);
4194 assert!(update_fail_malformed_htlcs.is_empty());
4195 assert!(update_fee.is_none());
4196 expected_next_node = node_id.clone();
4197 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4199 _ => panic!("Unexpected event"),
4202 assert!(events.is_empty());
4204 if !skip_last && idx == expected_route.len() - 1 {
4205 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4212 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4214 let events = origin_node.node.get_and_clear_pending_events();
4215 assert_eq!(events.len(), 1);
4217 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4218 assert_eq!(payment_hash, our_payment_hash);
4219 assert!(rejected_by_dest);
4221 _ => panic!("Unexpected event"),
4226 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
4227 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4230 fn create_network(node_count: usize) -> Vec<Node> {
4231 let mut nodes = Vec::new();
4232 let mut rng = thread_rng();
4233 let secp_ctx = Secp256k1::new();
4234 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
4236 let chan_count = Rc::new(RefCell::new(0));
4237 let payment_count = Rc::new(RefCell::new(0));
4239 for _ in 0..node_count {
4240 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4241 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4242 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4243 let mut seed = [0; 32];
4244 rng.fill_bytes(&mut seed);
4245 let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4246 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4247 let mut config = UserConfig::new();
4248 config.channel_options.announced_channel = true;
4249 config.channel_limits.force_announced_channel_preference = false;
4250 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();
4251 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4252 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4253 network_payment_count: payment_count.clone(),
4254 network_chan_count: chan_count.clone(),
4262 fn test_async_inbound_update_fee() {
4263 let mut nodes = create_network(2);
4264 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4265 let channel_id = chan.2;
4268 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4272 // send (1) commitment_signed -.
4273 // <- update_add_htlc/commitment_signed
4274 // send (2) RAA (awaiting remote revoke) -.
4275 // (1) commitment_signed is delivered ->
4276 // .- send (3) RAA (awaiting remote revoke)
4277 // (2) RAA is delivered ->
4278 // .- send (4) commitment_signed
4279 // <- (3) RAA is delivered
4280 // send (5) commitment_signed -.
4281 // <- (4) commitment_signed is delivered
4283 // (5) commitment_signed is delivered ->
4285 // (6) RAA is delivered ->
4287 // First nodes[0] generates an update_fee
4288 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4289 check_added_monitors!(nodes[0], 1);
4291 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4292 assert_eq!(events_0.len(), 1);
4293 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4294 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4295 (update_fee.as_ref(), commitment_signed)
4297 _ => panic!("Unexpected event"),
4300 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4302 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4303 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4304 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();
4305 check_added_monitors!(nodes[1], 1);
4307 let payment_event = {
4308 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4309 assert_eq!(events_1.len(), 1);
4310 SendEvent::from_event(events_1.remove(0))
4312 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4313 assert_eq!(payment_event.msgs.len(), 1);
4315 // ...now when the messages get delivered everyone should be happy
4316 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4317 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4318 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4319 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4320 check_added_monitors!(nodes[0], 1);
4322 // deliver(1), generate (3):
4323 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4324 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4325 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4326 check_added_monitors!(nodes[1], 1);
4328 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4329 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4330 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4331 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4332 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4333 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4334 assert!(bs_update.update_fee.is_none()); // (4)
4335 check_added_monitors!(nodes[1], 1);
4337 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4338 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4339 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4340 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4341 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4342 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4343 assert!(as_update.update_fee.is_none()); // (5)
4344 check_added_monitors!(nodes[0], 1);
4346 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4347 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4348 // only (6) so get_event_msg's assert(len == 1) passes
4349 check_added_monitors!(nodes[0], 1);
4351 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4352 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4353 check_added_monitors!(nodes[1], 1);
4355 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4356 check_added_monitors!(nodes[0], 1);
4358 let events_2 = nodes[0].node.get_and_clear_pending_events();
4359 assert_eq!(events_2.len(), 1);
4361 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4362 _ => panic!("Unexpected event"),
4365 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4366 check_added_monitors!(nodes[1], 1);
4370 fn test_update_fee_unordered_raa() {
4371 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4372 // crash in an earlier version of the update_fee patch)
4373 let mut nodes = create_network(2);
4374 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4375 let channel_id = chan.2;
4378 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4380 // First nodes[0] generates an update_fee
4381 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4382 check_added_monitors!(nodes[0], 1);
4384 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4385 assert_eq!(events_0.len(), 1);
4386 let update_msg = match events_0[0] { // (1)
4387 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4390 _ => panic!("Unexpected event"),
4393 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4395 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4396 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4397 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();
4398 check_added_monitors!(nodes[1], 1);
4400 let payment_event = {
4401 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4402 assert_eq!(events_1.len(), 1);
4403 SendEvent::from_event(events_1.remove(0))
4405 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4406 assert_eq!(payment_event.msgs.len(), 1);
4408 // ...now when the messages get delivered everyone should be happy
4409 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4410 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4411 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4412 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4413 check_added_monitors!(nodes[0], 1);
4415 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4416 check_added_monitors!(nodes[1], 1);
4418 // We can't continue, sadly, because our (1) now has a bogus signature
4422 fn test_multi_flight_update_fee() {
4423 let nodes = create_network(2);
4424 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4425 let channel_id = chan.2;
4428 // update_fee/commitment_signed ->
4429 // .- send (1) RAA and (2) commitment_signed
4430 // update_fee (never committed) ->
4431 // (3) update_fee ->
4432 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4433 // don't track which updates correspond to which revoke_and_ack responses so we're in
4434 // AwaitingRAA mode and will not generate the update_fee yet.
4435 // <- (1) RAA delivered
4436 // (3) is generated and send (4) CS -.
4437 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4438 // know the per_commitment_point to use for it.
4439 // <- (2) commitment_signed delivered
4440 // revoke_and_ack ->
4441 // B should send no response here
4442 // (4) commitment_signed delivered ->
4443 // <- RAA/commitment_signed delivered
4444 // revoke_and_ack ->
4446 // First nodes[0] generates an update_fee
4447 let initial_feerate = get_feerate!(nodes[0], channel_id);
4448 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4449 check_added_monitors!(nodes[0], 1);
4451 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4452 assert_eq!(events_0.len(), 1);
4453 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4454 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4455 (update_fee.as_ref().unwrap(), commitment_signed)
4457 _ => panic!("Unexpected event"),
4460 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4461 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4462 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4463 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4464 check_added_monitors!(nodes[1], 1);
4466 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4468 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4469 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4470 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4472 // Create the (3) update_fee message that nodes[0] will generate before it does...
4473 let mut update_msg_2 = msgs::UpdateFee {
4474 channel_id: update_msg_1.channel_id.clone(),
4475 feerate_per_kw: (initial_feerate + 30) as u32,
4478 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4480 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4482 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4484 // Deliver (1), generating (3) and (4)
4485 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4486 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4487 check_added_monitors!(nodes[0], 1);
4488 assert!(as_second_update.update_add_htlcs.is_empty());
4489 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4490 assert!(as_second_update.update_fail_htlcs.is_empty());
4491 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4492 // Check that the update_fee newly generated matches what we delivered:
4493 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4494 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4496 // Deliver (2) commitment_signed
4497 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4498 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4499 check_added_monitors!(nodes[0], 1);
4500 // No commitment_signed so get_event_msg's assert(len == 1) passes
4502 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4503 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4504 check_added_monitors!(nodes[1], 1);
4507 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4508 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4509 check_added_monitors!(nodes[1], 1);
4511 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4512 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4513 check_added_monitors!(nodes[0], 1);
4515 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4516 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4517 // No commitment_signed so get_event_msg's assert(len == 1) passes
4518 check_added_monitors!(nodes[0], 1);
4520 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4521 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4522 check_added_monitors!(nodes[1], 1);
4526 fn test_update_fee_vanilla() {
4527 let nodes = create_network(2);
4528 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4529 let channel_id = chan.2;
4531 let feerate = get_feerate!(nodes[0], channel_id);
4532 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4533 check_added_monitors!(nodes[0], 1);
4535 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4536 assert_eq!(events_0.len(), 1);
4537 let (update_msg, commitment_signed) = match events_0[0] {
4538 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 } } => {
4539 (update_fee.as_ref(), commitment_signed)
4541 _ => panic!("Unexpected event"),
4543 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4545 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4546 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4547 check_added_monitors!(nodes[1], 1);
4549 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4550 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4551 check_added_monitors!(nodes[0], 1);
4553 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4554 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4555 // No commitment_signed so get_event_msg's assert(len == 1) passes
4556 check_added_monitors!(nodes[0], 1);
4558 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4559 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4560 check_added_monitors!(nodes[1], 1);
4564 fn test_update_fee_that_funder_cannot_afford() {
4565 let nodes = create_network(2);
4566 let channel_value = 1888;
4567 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4568 let channel_id = chan.2;
4571 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4572 check_added_monitors!(nodes[0], 1);
4573 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4575 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4577 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4579 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4580 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4582 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4583 let chan = chan_lock.by_id.get(&channel_id).unwrap();
4585 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4586 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4587 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4588 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4589 actual_fee = channel_value - actual_fee;
4590 assert_eq!(total_fee, actual_fee);
4593 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4594 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4595 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4596 check_added_monitors!(nodes[0], 1);
4598 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4600 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4602 //While producing the commitment_signed response after handling a received update_fee request the
4603 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4604 //Should produce and error.
4605 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4607 assert!(match err.err {
4608 "Funding remote cannot afford proposed new fee" => true,
4612 //clear the message we could not handle
4613 nodes[1].node.get_and_clear_pending_msg_events();
4617 fn test_update_fee_with_fundee_update_add_htlc() {
4618 let mut nodes = create_network(2);
4619 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4620 let channel_id = chan.2;
4623 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4625 let feerate = get_feerate!(nodes[0], channel_id);
4626 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4627 check_added_monitors!(nodes[0], 1);
4629 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4630 assert_eq!(events_0.len(), 1);
4631 let (update_msg, commitment_signed) = match events_0[0] {
4632 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 } } => {
4633 (update_fee.as_ref(), commitment_signed)
4635 _ => panic!("Unexpected event"),
4637 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4638 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4639 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4640 check_added_monitors!(nodes[1], 1);
4642 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4644 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4646 // nothing happens since node[1] is in AwaitingRemoteRevoke
4647 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4649 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4650 assert_eq!(added_monitors.len(), 0);
4651 added_monitors.clear();
4653 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4654 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4655 // node[1] has nothing to do
4657 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4658 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4659 check_added_monitors!(nodes[0], 1);
4661 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4662 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4663 // No commitment_signed so get_event_msg's assert(len == 1) passes
4664 check_added_monitors!(nodes[0], 1);
4665 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4666 check_added_monitors!(nodes[1], 1);
4667 // AwaitingRemoteRevoke ends here
4669 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4670 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4671 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4672 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4673 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4674 assert_eq!(commitment_update.update_fee.is_none(), true);
4676 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4677 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4678 check_added_monitors!(nodes[0], 1);
4679 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4681 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4682 check_added_monitors!(nodes[1], 1);
4683 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4685 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4686 check_added_monitors!(nodes[1], 1);
4687 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4688 // No commitment_signed so get_event_msg's assert(len == 1) passes
4690 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4691 check_added_monitors!(nodes[0], 1);
4692 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4694 let events = nodes[0].node.get_and_clear_pending_events();
4695 assert_eq!(events.len(), 1);
4697 Event::PendingHTLCsForwardable { .. } => { },
4698 _ => panic!("Unexpected event"),
4700 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4701 nodes[0].node.process_pending_htlc_forwards();
4703 let events = nodes[0].node.get_and_clear_pending_events();
4704 assert_eq!(events.len(), 1);
4706 Event::PaymentReceived { .. } => { },
4707 _ => panic!("Unexpected event"),
4710 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4712 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4713 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4714 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4718 fn test_update_fee() {
4719 let nodes = create_network(2);
4720 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4721 let channel_id = chan.2;
4724 // (1) update_fee/commitment_signed ->
4725 // <- (2) revoke_and_ack
4726 // .- send (3) commitment_signed
4727 // (4) update_fee/commitment_signed ->
4728 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4729 // <- (3) commitment_signed delivered
4730 // send (6) revoke_and_ack -.
4731 // <- (5) deliver revoke_and_ack
4732 // (6) deliver revoke_and_ack ->
4733 // .- send (7) commitment_signed in response to (4)
4734 // <- (7) deliver commitment_signed
4735 // revoke_and_ack ->
4737 // Create and deliver (1)...
4738 let feerate = get_feerate!(nodes[0], channel_id);
4739 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4740 check_added_monitors!(nodes[0], 1);
4742 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4743 assert_eq!(events_0.len(), 1);
4744 let (update_msg, commitment_signed) = match events_0[0] {
4745 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 } } => {
4746 (update_fee.as_ref(), commitment_signed)
4748 _ => panic!("Unexpected event"),
4750 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4752 // Generate (2) and (3):
4753 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4754 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4755 check_added_monitors!(nodes[1], 1);
4758 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4759 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4760 check_added_monitors!(nodes[0], 1);
4762 // Create and deliver (4)...
4763 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4764 check_added_monitors!(nodes[0], 1);
4765 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4766 assert_eq!(events_0.len(), 1);
4767 let (update_msg, commitment_signed) = match events_0[0] {
4768 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 } } => {
4769 (update_fee.as_ref(), commitment_signed)
4771 _ => panic!("Unexpected event"),
4774 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4776 check_added_monitors!(nodes[1], 1);
4778 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4779 // No commitment_signed so get_event_msg's assert(len == 1) passes
4781 // Handle (3), creating (6):
4782 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4783 check_added_monitors!(nodes[0], 1);
4784 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4785 // No commitment_signed so get_event_msg's assert(len == 1) passes
4788 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4789 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4790 check_added_monitors!(nodes[0], 1);
4792 // Deliver (6), creating (7):
4793 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4794 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4795 assert!(commitment_update.update_add_htlcs.is_empty());
4796 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4797 assert!(commitment_update.update_fail_htlcs.is_empty());
4798 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4799 assert!(commitment_update.update_fee.is_none());
4800 check_added_monitors!(nodes[1], 1);
4803 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4804 check_added_monitors!(nodes[0], 1);
4805 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4806 // No commitment_signed so get_event_msg's assert(len == 1) passes
4808 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4809 check_added_monitors!(nodes[1], 1);
4810 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4812 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4813 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4814 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4818 fn pre_funding_lock_shutdown_test() {
4819 // Test sending a shutdown prior to funding_locked after funding generation
4820 let nodes = create_network(2);
4821 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4822 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4823 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4824 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4826 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4827 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4828 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4829 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4830 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4832 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4833 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4834 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4835 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4836 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4837 assert!(node_0_none.is_none());
4839 assert!(nodes[0].node.list_channels().is_empty());
4840 assert!(nodes[1].node.list_channels().is_empty());
4844 fn updates_shutdown_wait() {
4845 // Test sending a shutdown with outstanding updates pending
4846 let mut nodes = create_network(3);
4847 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4848 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4849 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4850 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4852 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4854 nodes[0].node.close_channel(&chan_1.2).unwrap();
4855 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4856 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4857 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4858 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4860 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4861 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4863 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4864 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4865 else { panic!("New sends should fail!") };
4866 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4867 else { panic!("New sends should fail!") };
4869 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4870 check_added_monitors!(nodes[2], 1);
4871 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4872 assert!(updates.update_add_htlcs.is_empty());
4873 assert!(updates.update_fail_htlcs.is_empty());
4874 assert!(updates.update_fail_malformed_htlcs.is_empty());
4875 assert!(updates.update_fee.is_none());
4876 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4877 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4878 check_added_monitors!(nodes[1], 1);
4879 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4880 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4882 assert!(updates_2.update_add_htlcs.is_empty());
4883 assert!(updates_2.update_fail_htlcs.is_empty());
4884 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4885 assert!(updates_2.update_fee.is_none());
4886 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4887 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4888 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4890 let events = nodes[0].node.get_and_clear_pending_events();
4891 assert_eq!(events.len(), 1);
4893 Event::PaymentSent { ref payment_preimage } => {
4894 assert_eq!(our_payment_preimage, *payment_preimage);
4896 _ => panic!("Unexpected event"),
4899 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4900 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4901 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4902 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4903 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4904 assert!(node_0_none.is_none());
4906 assert!(nodes[0].node.list_channels().is_empty());
4908 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4909 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4910 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4911 assert!(nodes[1].node.list_channels().is_empty());
4912 assert!(nodes[2].node.list_channels().is_empty());
4916 fn htlc_fail_async_shutdown() {
4917 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4918 let mut nodes = create_network(3);
4919 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4920 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4922 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4923 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4924 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4925 check_added_monitors!(nodes[0], 1);
4926 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4927 assert_eq!(updates.update_add_htlcs.len(), 1);
4928 assert!(updates.update_fulfill_htlcs.is_empty());
4929 assert!(updates.update_fail_htlcs.is_empty());
4930 assert!(updates.update_fail_malformed_htlcs.is_empty());
4931 assert!(updates.update_fee.is_none());
4933 nodes[1].node.close_channel(&chan_1.2).unwrap();
4934 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4935 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4936 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4938 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4939 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4940 check_added_monitors!(nodes[1], 1);
4941 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4942 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4944 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4945 assert!(updates_2.update_add_htlcs.is_empty());
4946 assert!(updates_2.update_fulfill_htlcs.is_empty());
4947 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4948 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4949 assert!(updates_2.update_fee.is_none());
4951 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
4952 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4954 let events = nodes[0].node.get_and_clear_pending_events();
4955 assert_eq!(events.len(), 1);
4957 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
4958 assert_eq!(our_payment_hash, *payment_hash);
4959 assert!(!rejected_by_dest);
4961 _ => panic!("Unexpected event"),
4964 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4965 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4966 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4967 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4968 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4969 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4970 assert!(node_0_none.is_none());
4972 assert!(nodes[0].node.list_channels().is_empty());
4974 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4975 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4976 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4977 assert!(nodes[1].node.list_channels().is_empty());
4978 assert!(nodes[2].node.list_channels().is_empty());
4982 fn update_fee_async_shutdown() {
4983 // Test update_fee works after shutdown start if messages are delivered out-of-order
4984 let nodes = create_network(2);
4985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4987 let starting_feerate = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().get_feerate();
4988 nodes[0].node.update_fee(chan_1.2.clone(), starting_feerate + 20).unwrap();
4989 check_added_monitors!(nodes[0], 1);
4990 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4991 assert!(updates.update_add_htlcs.is_empty());
4992 assert!(updates.update_fulfill_htlcs.is_empty());
4993 assert!(updates.update_fail_htlcs.is_empty());
4994 assert!(updates.update_fail_malformed_htlcs.is_empty());
4995 assert!(updates.update_fee.is_some());
4997 nodes[1].node.close_channel(&chan_1.2).unwrap();
4998 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4999 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5000 // Note that we don't actually test normative behavior here. The spec indicates we could
5001 // actually send a closing_signed here, but is kinda unclear and could possibly be amended
5002 // to require waiting on the full commitment dance before doing so (see
5003 // https://github.com/lightningnetwork/lightning-rfc/issues/499). In any case, to avoid
5004 // ambiguity, we should wait until after the full commitment dance to send closing_signed.
5005 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5007 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &updates.update_fee.unwrap()).unwrap();
5008 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5009 check_added_monitors!(nodes[1], 1);
5010 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5011 let node_0_closing_signed = commitment_signed_dance!(nodes[1], nodes[0], (), false, true, true);
5013 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5014 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), match node_0_closing_signed.unwrap() {
5015 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5016 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5019 _ => panic!("Unexpected event"),
5021 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5022 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5023 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5024 assert!(node_0_none.is_none());
5027 fn do_test_shutdown_rebroadcast(recv_count: u8) {
5028 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5029 // messages delivered prior to disconnect
5030 let nodes = create_network(3);
5031 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5032 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5034 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5036 nodes[1].node.close_channel(&chan_1.2).unwrap();
5037 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5039 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5040 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5042 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5046 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5047 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5049 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5050 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5051 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5052 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5054 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5055 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5056 assert!(node_1_shutdown == node_1_2nd_shutdown);
5058 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5059 let node_0_2nd_shutdown = if recv_count > 0 {
5060 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5061 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5064 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5065 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5066 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5068 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5070 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5071 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5073 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5074 check_added_monitors!(nodes[2], 1);
5075 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5076 assert!(updates.update_add_htlcs.is_empty());
5077 assert!(updates.update_fail_htlcs.is_empty());
5078 assert!(updates.update_fail_malformed_htlcs.is_empty());
5079 assert!(updates.update_fee.is_none());
5080 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5081 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5082 check_added_monitors!(nodes[1], 1);
5083 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5084 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5086 assert!(updates_2.update_add_htlcs.is_empty());
5087 assert!(updates_2.update_fail_htlcs.is_empty());
5088 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5089 assert!(updates_2.update_fee.is_none());
5090 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5091 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5092 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5094 let events = nodes[0].node.get_and_clear_pending_events();
5095 assert_eq!(events.len(), 1);
5097 Event::PaymentSent { ref payment_preimage } => {
5098 assert_eq!(our_payment_preimage, *payment_preimage);
5100 _ => panic!("Unexpected event"),
5103 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5105 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5106 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5107 assert!(node_1_closing_signed.is_some());
5110 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5111 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5113 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5114 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5115 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5116 if recv_count == 0 {
5117 // If all closing_signeds weren't delivered we can just resume where we left off...
5118 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5120 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5121 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5122 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5124 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5125 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5126 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5128 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5129 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5131 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5132 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5133 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5135 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5136 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5137 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5138 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5139 assert!(node_0_none.is_none());
5141 // If one node, however, received + responded with an identical closing_signed we end
5142 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5143 // There isn't really anything better we can do simply, but in the future we might
5144 // explore storing a set of recently-closed channels that got disconnected during
5145 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5146 // give our counterparty enough time to (potentially) broadcast a cooperative closing
5148 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5150 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5151 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5152 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5153 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5154 assert_eq!(*channel_id, chan_1.2);
5155 } else { panic!("Needed SendErrorMessage close"); }
5157 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5158 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5159 // closing_signed so we do it ourselves
5160 let events = nodes[0].node.get_and_clear_pending_msg_events();
5161 assert_eq!(events.len(), 1);
5163 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5164 assert_eq!(msg.contents.flags & 2, 2);
5166 _ => panic!("Unexpected event"),
5170 assert!(nodes[0].node.list_channels().is_empty());
5172 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5173 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5174 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5175 assert!(nodes[1].node.list_channels().is_empty());
5176 assert!(nodes[2].node.list_channels().is_empty());
5180 fn test_shutdown_rebroadcast() {
5181 do_test_shutdown_rebroadcast(0);
5182 do_test_shutdown_rebroadcast(1);
5183 do_test_shutdown_rebroadcast(2);
5187 fn fake_network_test() {
5188 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5189 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5190 let nodes = create_network(4);
5192 // Create some initial channels
5193 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5194 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5195 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5197 // Rebalance the network a bit by relaying one payment through all the channels...
5198 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5199 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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);
5203 // Send some more payments
5204 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5205 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5206 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5208 // Test failure packets
5209 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5210 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5212 // Add a new channel that skips 3
5213 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5215 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5216 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5217 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5218 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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);
5223 // Do some rebalance loop payments, simultaneously
5224 let mut hops = Vec::with_capacity(3);
5225 hops.push(RouteHop {
5226 pubkey: nodes[2].node.get_our_node_id(),
5227 short_channel_id: chan_2.0.contents.short_channel_id,
5229 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5231 hops.push(RouteHop {
5232 pubkey: nodes[3].node.get_our_node_id(),
5233 short_channel_id: chan_3.0.contents.short_channel_id,
5235 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5237 hops.push(RouteHop {
5238 pubkey: nodes[1].node.get_our_node_id(),
5239 short_channel_id: chan_4.0.contents.short_channel_id,
5241 cltv_expiry_delta: TEST_FINAL_CLTV,
5243 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;
5244 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;
5245 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5247 let mut hops = Vec::with_capacity(3);
5248 hops.push(RouteHop {
5249 pubkey: nodes[3].node.get_our_node_id(),
5250 short_channel_id: chan_4.0.contents.short_channel_id,
5252 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5254 hops.push(RouteHop {
5255 pubkey: nodes[2].node.get_our_node_id(),
5256 short_channel_id: chan_3.0.contents.short_channel_id,
5258 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5260 hops.push(RouteHop {
5261 pubkey: nodes[1].node.get_our_node_id(),
5262 short_channel_id: chan_2.0.contents.short_channel_id,
5264 cltv_expiry_delta: TEST_FINAL_CLTV,
5266 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;
5267 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;
5268 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5270 // Claim the rebalances...
5271 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5272 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5274 // Add a duplicate new channel from 2 to 4
5275 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5277 // Send some payments across both channels
5278 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5279 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5280 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5282 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5284 //TODO: Test that routes work again here as we've been notified that the channel is full
5286 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5287 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5288 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5290 // Close down the channels...
5291 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5292 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5293 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5294 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5295 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5299 fn duplicate_htlc_test() {
5300 // Test that we accept duplicate payment_hash HTLCs across the network and that
5301 // claiming/failing them are all separate and don't effect each other
5302 let mut nodes = create_network(6);
5304 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5305 create_announced_chan_between_nodes(&nodes, 0, 3);
5306 create_announced_chan_between_nodes(&nodes, 1, 3);
5307 create_announced_chan_between_nodes(&nodes, 2, 3);
5308 create_announced_chan_between_nodes(&nodes, 3, 4);
5309 create_announced_chan_between_nodes(&nodes, 3, 5);
5311 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5313 *nodes[0].network_payment_count.borrow_mut() -= 1;
5314 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5316 *nodes[0].network_payment_count.borrow_mut() -= 1;
5317 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5319 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5320 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5321 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5324 #[derive(PartialEq)]
5325 enum HTLCType { NONE, TIMEOUT, SUCCESS }
5326 /// Tests that the given node has broadcast transactions for the given Channel
5328 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5329 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5330 /// broadcast and the revoked outputs were claimed.
5332 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5333 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5335 /// All broadcast transactions must be accounted for in one of the above three types of we'll
5337 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5338 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5339 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5341 let mut res = Vec::with_capacity(2);
5342 node_txn.retain(|tx| {
5343 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5344 check_spends!(tx, chan.3.clone());
5345 if commitment_tx.is_none() {
5346 res.push(tx.clone());
5351 if let Some(explicit_tx) = commitment_tx {
5352 res.push(explicit_tx.clone());
5355 assert_eq!(res.len(), 1);
5357 if has_htlc_tx != HTLCType::NONE {
5358 node_txn.retain(|tx| {
5359 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5360 check_spends!(tx, res[0].clone());
5361 if has_htlc_tx == HTLCType::TIMEOUT {
5362 assert!(tx.lock_time != 0);
5364 assert!(tx.lock_time == 0);
5366 res.push(tx.clone());
5370 assert_eq!(res.len(), 2);
5373 assert!(node_txn.is_empty());
5377 /// Tests that the given node has broadcast a claim transaction against the provided revoked
5378 /// HTLC transaction.
5379 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5380 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5381 assert_eq!(node_txn.len(), 1);
5382 node_txn.retain(|tx| {
5383 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5384 check_spends!(tx, revoked_tx.clone());
5388 assert!(node_txn.is_empty());
5391 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5392 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5394 assert!(node_txn.len() >= 1);
5395 assert_eq!(node_txn[0].input.len(), 1);
5396 let mut found_prev = false;
5398 for tx in prev_txn {
5399 if node_txn[0].input[0].previous_output.txid == tx.txid() {
5400 check_spends!(node_txn[0], tx.clone());
5401 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5402 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5408 assert!(found_prev);
5410 let mut res = Vec::new();
5411 mem::swap(&mut *node_txn, &mut res);
5415 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5416 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5417 assert_eq!(events_1.len(), 1);
5418 let as_update = match events_1[0] {
5419 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5422 _ => panic!("Unexpected event"),
5425 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5426 assert_eq!(events_2.len(), 1);
5427 let bs_update = match events_2[0] {
5428 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5431 _ => panic!("Unexpected event"),
5435 node.router.handle_channel_update(&as_update).unwrap();
5436 node.router.handle_channel_update(&bs_update).unwrap();
5440 macro_rules! expect_pending_htlcs_forwardable {
5442 let events = $node.node.get_and_clear_pending_events();
5443 assert_eq!(events.len(), 1);
5445 Event::PendingHTLCsForwardable { .. } => { },
5446 _ => panic!("Unexpected event"),
5448 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5449 $node.node.process_pending_htlc_forwards();
5453 fn do_channel_reserve_test(test_recv: bool) {
5455 use std::sync::atomic::Ordering;
5456 use ln::msgs::HandleError;
5458 macro_rules! get_channel_value_stat {
5459 ($node: expr, $channel_id: expr) => {{
5460 let chan_lock = $node.node.channel_state.lock().unwrap();
5461 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5462 chan.get_value_stat()
5466 let mut nodes = create_network(3);
5467 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5468 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5470 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5471 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5473 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5474 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5476 macro_rules! get_route_and_payment_hash {
5477 ($recv_value: expr) => {{
5478 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5479 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5480 (route, payment_hash, payment_preimage)
5484 macro_rules! expect_forward {
5486 let mut events = $node.node.get_and_clear_pending_msg_events();
5487 assert_eq!(events.len(), 1);
5488 check_added_monitors!($node, 1);
5489 let payment_event = SendEvent::from_event(events.remove(0));
5494 macro_rules! expect_payment_received {
5495 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5496 let events = $node.node.get_and_clear_pending_events();
5497 assert_eq!(events.len(), 1);
5499 Event::PaymentReceived { ref payment_hash, amt } => {
5500 assert_eq!($expected_payment_hash, *payment_hash);
5501 assert_eq!($expected_recv_value, amt);
5503 _ => panic!("Unexpected event"),
5508 let feemsat = 239; // somehow we know?
5509 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5511 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5513 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5515 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5516 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5517 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5519 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5520 _ => panic!("Unknown error variants"),
5524 let mut htlc_id = 0;
5525 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5526 // nodes[0]'s wealth
5528 let amt_msat = recv_value_0 + total_fee_msat;
5529 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5532 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5535 let (stat01_, stat11_, stat12_, stat22_) = (
5536 get_channel_value_stat!(nodes[0], chan_1.2),
5537 get_channel_value_stat!(nodes[1], chan_1.2),
5538 get_channel_value_stat!(nodes[1], chan_2.2),
5539 get_channel_value_stat!(nodes[2], chan_2.2),
5542 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5543 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5544 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5545 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5546 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5550 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5551 // attempt to get channel_reserve violation
5552 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5553 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5555 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5556 _ => panic!("Unknown error variants"),
5560 // adding pending output
5561 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5562 let amt_msat_1 = recv_value_1 + total_fee_msat;
5564 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5565 let payment_event_1 = {
5566 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5567 check_added_monitors!(nodes[0], 1);
5569 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5570 assert_eq!(events.len(), 1);
5571 SendEvent::from_event(events.remove(0))
5573 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5575 // channel reserve test with htlc pending output > 0
5576 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5578 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5579 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5580 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5581 _ => panic!("Unknown error variants"),
5586 // test channel_reserve test on nodes[1] side
5587 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5589 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5590 let secp_ctx = Secp256k1::new();
5591 let session_priv = SecretKey::from_slice(&secp_ctx, &{
5592 let mut session_key = [0; 32];
5593 rng::fill_bytes(&mut session_key);
5595 }).expect("RNG is bad!");
5597 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5598 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5599 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5600 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5601 let msg = msgs::UpdateAddHTLC {
5602 channel_id: chan_1.2,
5604 amount_msat: htlc_msat,
5605 payment_hash: our_payment_hash,
5606 cltv_expiry: htlc_cltv,
5607 onion_routing_packet: onion_packet,
5611 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5613 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5615 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5616 assert_eq!(nodes[1].node.list_channels().len(), 1);
5617 assert_eq!(nodes[1].node.list_channels().len(), 1);
5618 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5619 assert_eq!(channel_close_broadcast.len(), 1);
5620 match channel_close_broadcast[0] {
5621 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5622 assert_eq!(msg.contents.flags & 2, 2);
5624 _ => panic!("Unexpected event"),
5630 // split the rest to test holding cell
5631 let recv_value_21 = recv_value_2/2;
5632 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5634 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5635 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);
5638 // now see if they go through on both sides
5639 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5640 // but this will stuck in the holding cell
5641 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5642 check_added_monitors!(nodes[0], 0);
5643 let events = nodes[0].node.get_and_clear_pending_events();
5644 assert_eq!(events.len(), 0);
5646 // test with outbound holding cell amount > 0
5648 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5649 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5650 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5651 _ => panic!("Unknown error variants"),
5655 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5656 // this will also stuck in the holding cell
5657 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5658 check_added_monitors!(nodes[0], 0);
5659 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5660 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5662 // flush the pending htlc
5663 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5664 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5665 check_added_monitors!(nodes[1], 1);
5667 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5668 check_added_monitors!(nodes[0], 1);
5669 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5671 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5672 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5673 // No commitment_signed so get_event_msg's assert(len == 1) passes
5674 check_added_monitors!(nodes[0], 1);
5676 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5677 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5678 check_added_monitors!(nodes[1], 1);
5680 expect_pending_htlcs_forwardable!(nodes[1]);
5682 let ref payment_event_11 = expect_forward!(nodes[1]);
5683 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5684 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5686 expect_pending_htlcs_forwardable!(nodes[2]);
5687 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5689 // flush the htlcs in the holding cell
5690 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5691 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5692 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5693 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5694 expect_pending_htlcs_forwardable!(nodes[1]);
5696 let ref payment_event_3 = expect_forward!(nodes[1]);
5697 assert_eq!(payment_event_3.msgs.len(), 2);
5698 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5699 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5701 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5702 expect_pending_htlcs_forwardable!(nodes[2]);
5704 let events = nodes[2].node.get_and_clear_pending_events();
5705 assert_eq!(events.len(), 2);
5707 Event::PaymentReceived { ref payment_hash, amt } => {
5708 assert_eq!(our_payment_hash_21, *payment_hash);
5709 assert_eq!(recv_value_21, amt);
5711 _ => panic!("Unexpected event"),
5714 Event::PaymentReceived { ref payment_hash, amt } => {
5715 assert_eq!(our_payment_hash_22, *payment_hash);
5716 assert_eq!(recv_value_22, amt);
5718 _ => panic!("Unexpected event"),
5721 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5722 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5723 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5725 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);
5726 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5727 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5728 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5730 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5731 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5735 fn channel_reserve_test() {
5736 do_channel_reserve_test(false);
5737 do_channel_reserve_test(true);
5741 fn channel_monitor_network_test() {
5742 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5743 // tests that ChannelMonitor is able to recover from various states.
5744 let nodes = create_network(5);
5746 // Create some initial channels
5747 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5748 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5749 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5750 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5752 // Rebalance the network a bit by relaying one payment through all the channels...
5753 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5754 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5755 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5756 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5758 // Simple case with no pending HTLCs:
5759 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5761 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5762 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5763 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5764 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5766 get_announce_close_broadcast_events(&nodes, 0, 1);
5767 assert_eq!(nodes[0].node.list_channels().len(), 0);
5768 assert_eq!(nodes[1].node.list_channels().len(), 1);
5770 // One pending HTLC is discarded by the force-close:
5771 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5773 // Simple case of one pending HTLC to HTLC-Timeout
5774 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5776 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5777 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5778 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5779 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5781 get_announce_close_broadcast_events(&nodes, 1, 2);
5782 assert_eq!(nodes[1].node.list_channels().len(), 0);
5783 assert_eq!(nodes[2].node.list_channels().len(), 1);
5785 macro_rules! claim_funds {
5786 ($node: expr, $prev_node: expr, $preimage: expr) => {
5788 assert!($node.node.claim_funds($preimage));
5789 check_added_monitors!($node, 1);
5791 let events = $node.node.get_and_clear_pending_msg_events();
5792 assert_eq!(events.len(), 1);
5794 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5795 assert!(update_add_htlcs.is_empty());
5796 assert!(update_fail_htlcs.is_empty());
5797 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5799 _ => panic!("Unexpected event"),
5805 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5806 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5807 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5809 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5811 // Claim the payment on nodes[3], giving it knowledge of the preimage
5812 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5814 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5815 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5817 check_preimage_claim(&nodes[3], &node_txn);
5819 get_announce_close_broadcast_events(&nodes, 2, 3);
5820 assert_eq!(nodes[2].node.list_channels().len(), 0);
5821 assert_eq!(nodes[3].node.list_channels().len(), 1);
5823 { // Cheat and reset nodes[4]'s height to 1
5824 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5825 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5828 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5829 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5830 // One pending HTLC to time out:
5831 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5832 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5836 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5837 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5838 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5839 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5840 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5843 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5845 // Claim the payment on nodes[4], giving it knowledge of the preimage
5846 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5848 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5849 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5850 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5851 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5852 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5855 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5857 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5858 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5860 check_preimage_claim(&nodes[4], &node_txn);
5862 get_announce_close_broadcast_events(&nodes, 3, 4);
5863 assert_eq!(nodes[3].node.list_channels().len(), 0);
5864 assert_eq!(nodes[4].node.list_channels().len(), 0);
5868 fn test_justice_tx() {
5869 // Test justice txn built on revoked HTLC-Success tx, against both sides
5871 let nodes = create_network(2);
5872 // Create some new channels:
5873 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5875 // A pending HTLC which will be revoked:
5876 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5877 // Get the will-be-revoked local txn from nodes[0]
5878 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5879 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5880 assert_eq!(revoked_local_txn[0].input.len(), 1);
5881 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5882 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5883 assert_eq!(revoked_local_txn[1].input.len(), 1);
5884 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5885 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
5886 // Revoke the old state
5887 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5890 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5891 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5893 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5894 assert_eq!(node_txn.len(), 3);
5895 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5896 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5898 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5899 node_txn.swap_remove(0);
5901 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5903 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5904 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5905 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5906 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5907 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5909 get_announce_close_broadcast_events(&nodes, 0, 1);
5911 assert_eq!(nodes[0].node.list_channels().len(), 0);
5912 assert_eq!(nodes[1].node.list_channels().len(), 0);
5914 // We test justice_tx build by A on B's revoked HTLC-Success tx
5915 // Create some new channels:
5916 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5918 // A pending HTLC which will be revoked:
5919 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5920 // Get the will-be-revoked local txn from B
5921 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5922 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5923 assert_eq!(revoked_local_txn[0].input.len(), 1);
5924 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5925 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5926 // Revoke the old state
5927 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5929 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5930 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5932 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5933 assert_eq!(node_txn.len(), 3);
5934 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5935 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5937 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5938 node_txn.swap_remove(0);
5940 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5942 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5943 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5944 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5945 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5946 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5948 get_announce_close_broadcast_events(&nodes, 0, 1);
5949 assert_eq!(nodes[0].node.list_channels().len(), 0);
5950 assert_eq!(nodes[1].node.list_channels().len(), 0);
5954 fn revoked_output_claim() {
5955 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5956 // transaction is broadcast by its counterparty
5957 let nodes = create_network(2);
5958 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5959 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5960 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5961 assert_eq!(revoked_local_txn.len(), 1);
5962 // Only output is the full channel value back to nodes[0]:
5963 assert_eq!(revoked_local_txn[0].output.len(), 1);
5964 // Send a payment through, updating everyone's latest commitment txn
5965 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5967 // Inform nodes[1] that nodes[0] broadcast a stale tx
5968 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5969 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5970 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5971 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5973 assert_eq!(node_txn[0], node_txn[2]);
5975 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5976 check_spends!(node_txn[1], chan_1.3.clone());
5978 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5979 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5980 get_announce_close_broadcast_events(&nodes, 0, 1);
5984 fn claim_htlc_outputs_shared_tx() {
5985 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5986 let nodes = create_network(2);
5988 // Create some new channel:
5989 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5991 // Rebalance the network to generate htlc in the two directions
5992 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5993 // 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
5994 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5995 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
5997 // Get the will-be-revoked local txn from node[0]
5998 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5999 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6000 assert_eq!(revoked_local_txn[0].input.len(), 1);
6001 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6002 assert_eq!(revoked_local_txn[1].input.len(), 1);
6003 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6004 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
6005 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6007 //Revoke the old state
6008 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6011 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6013 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6015 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6016 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6017 assert_eq!(node_txn.len(), 4);
6019 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6020 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6022 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6024 let mut witness_lens = BTreeSet::new();
6025 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6026 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6027 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6028 assert_eq!(witness_lens.len(), 3);
6029 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6030 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
6031 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
6033 // Next nodes[1] broadcasts its current local tx state:
6034 assert_eq!(node_txn[1].input.len(), 1);
6035 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6037 assert_eq!(node_txn[2].input.len(), 1);
6038 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6039 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
6040 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6041 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6042 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6044 get_announce_close_broadcast_events(&nodes, 0, 1);
6045 assert_eq!(nodes[0].node.list_channels().len(), 0);
6046 assert_eq!(nodes[1].node.list_channels().len(), 0);
6050 fn claim_htlc_outputs_single_tx() {
6051 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6052 let nodes = create_network(2);
6054 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6056 // Rebalance the network to generate htlc in the two directions
6057 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6058 // 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
6059 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6060 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6061 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
6063 // Get the will-be-revoked local txn from node[0]
6064 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6066 //Revoke the old state
6067 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6070 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6072 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6074 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6075 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6076 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)
6078 assert_eq!(node_txn[0], node_txn[7]);
6079 assert_eq!(node_txn[1], node_txn[8]);
6080 assert_eq!(node_txn[2], node_txn[9]);
6081 assert_eq!(node_txn[3], node_txn[10]);
6082 assert_eq!(node_txn[4], node_txn[11]);
6083 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6084 assert_eq!(node_txn[4], node_txn[6]);
6086 assert_eq!(node_txn[0].input.len(), 1);
6087 assert_eq!(node_txn[1].input.len(), 1);
6088 assert_eq!(node_txn[2].input.len(), 1);
6090 let mut revoked_tx_map = HashMap::new();
6091 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6092 node_txn[0].verify(&revoked_tx_map).unwrap();
6093 node_txn[1].verify(&revoked_tx_map).unwrap();
6094 node_txn[2].verify(&revoked_tx_map).unwrap();
6096 let mut witness_lens = BTreeSet::new();
6097 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6098 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6099 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6100 assert_eq!(witness_lens.len(), 3);
6101 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6102 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
6103 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
6105 assert_eq!(node_txn[3].input.len(), 1);
6106 check_spends!(node_txn[3], chan_1.3.clone());
6108 assert_eq!(node_txn[4].input.len(), 1);
6109 let witness_script = node_txn[4].input[0].witness.last().unwrap();
6110 assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
6111 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6112 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6113 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6115 get_announce_close_broadcast_events(&nodes, 0, 1);
6116 assert_eq!(nodes[0].node.list_channels().len(), 0);
6117 assert_eq!(nodes[1].node.list_channels().len(), 0);
6121 fn test_htlc_ignore_latest_remote_commitment() {
6122 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6123 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6124 let nodes = create_network(2);
6125 create_announced_chan_between_nodes(&nodes, 0, 1);
6127 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6128 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6130 let events = nodes[0].node.get_and_clear_pending_msg_events();
6131 assert_eq!(events.len(), 1);
6133 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6134 assert_eq!(flags & 0b10, 0b10);
6136 _ => panic!("Unexpected event"),
6140 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6141 assert_eq!(node_txn.len(), 2);
6143 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6144 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6147 let events = nodes[1].node.get_and_clear_pending_msg_events();
6148 assert_eq!(events.len(), 1);
6150 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6151 assert_eq!(flags & 0b10, 0b10);
6153 _ => panic!("Unexpected event"),
6157 // Duplicate the block_connected call since this may happen due to other listeners
6158 // registering new transactions
6159 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6163 fn test_force_close_fail_back() {
6164 // Check which HTLCs are failed-backwards on channel force-closure
6165 let mut nodes = create_network(3);
6166 create_announced_chan_between_nodes(&nodes, 0, 1);
6167 create_announced_chan_between_nodes(&nodes, 1, 2);
6169 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6171 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6173 let mut payment_event = {
6174 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6175 check_added_monitors!(nodes[0], 1);
6177 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6178 assert_eq!(events.len(), 1);
6179 SendEvent::from_event(events.remove(0))
6182 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6183 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6185 let events_1 = nodes[1].node.get_and_clear_pending_events();
6186 assert_eq!(events_1.len(), 1);
6188 Event::PendingHTLCsForwardable { .. } => { },
6189 _ => panic!("Unexpected event"),
6192 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6193 nodes[1].node.process_pending_htlc_forwards();
6195 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6196 assert_eq!(events_2.len(), 1);
6197 payment_event = SendEvent::from_event(events_2.remove(0));
6198 assert_eq!(payment_event.msgs.len(), 1);
6200 check_added_monitors!(nodes[1], 1);
6201 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6202 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6203 check_added_monitors!(nodes[2], 1);
6204 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6206 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6207 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6208 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6210 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6211 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6212 assert_eq!(events_3.len(), 1);
6214 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6215 assert_eq!(flags & 0b10, 0b10);
6217 _ => panic!("Unexpected event"),
6221 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6222 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6223 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6224 // back to nodes[1] upon timeout otherwise.
6225 assert_eq!(node_txn.len(), 1);
6229 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6230 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6232 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6233 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6234 assert_eq!(events_4.len(), 1);
6236 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6237 assert_eq!(flags & 0b10, 0b10);
6239 _ => panic!("Unexpected event"),
6242 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6244 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6245 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6246 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6248 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6249 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6250 assert_eq!(node_txn.len(), 1);
6251 assert_eq!(node_txn[0].input.len(), 1);
6252 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6253 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6254 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6256 check_spends!(node_txn[0], tx);
6260 fn test_unconf_chan() {
6261 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6262 let nodes = create_network(2);
6263 create_announced_chan_between_nodes(&nodes, 0, 1);
6265 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6266 assert_eq!(channel_state.by_id.len(), 1);
6267 assert_eq!(channel_state.short_to_id.len(), 1);
6268 mem::drop(channel_state);
6270 let mut headers = Vec::new();
6271 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6272 headers.push(header.clone());
6274 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6275 headers.push(header.clone());
6277 while !headers.is_empty() {
6278 nodes[0].node.block_disconnected(&headers.pop().unwrap());
6281 let events = nodes[0].node.get_and_clear_pending_msg_events();
6282 assert_eq!(events.len(), 1);
6284 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6285 assert_eq!(flags & 0b10, 0b10);
6287 _ => panic!("Unexpected event"),
6290 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6291 assert_eq!(channel_state.by_id.len(), 0);
6292 assert_eq!(channel_state.short_to_id.len(), 0);
6295 macro_rules! get_chan_reestablish_msgs {
6296 ($src_node: expr, $dst_node: expr) => {
6298 let mut res = Vec::with_capacity(1);
6299 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6300 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6301 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6302 res.push(msg.clone());
6304 panic!("Unexpected event")
6312 macro_rules! handle_chan_reestablish_msgs {
6313 ($src_node: expr, $dst_node: expr) => {
6315 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6317 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6319 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6325 let mut revoke_and_ack = None;
6326 let mut commitment_update = None;
6327 let order = if let Some(ev) = msg_events.get(idx) {
6330 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6331 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6332 revoke_and_ack = Some(msg.clone());
6333 RAACommitmentOrder::RevokeAndACKFirst
6335 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6336 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6337 commitment_update = Some(updates.clone());
6338 RAACommitmentOrder::CommitmentFirst
6340 _ => panic!("Unexpected event"),
6343 RAACommitmentOrder::CommitmentFirst
6346 if let Some(ev) = msg_events.get(idx) {
6348 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6349 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6350 assert!(revoke_and_ack.is_none());
6351 revoke_and_ack = Some(msg.clone());
6353 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6354 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6355 assert!(commitment_update.is_none());
6356 commitment_update = Some(updates.clone());
6358 _ => panic!("Unexpected event"),
6362 (funding_locked, revoke_and_ack, commitment_update, order)
6367 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6368 /// for claims/fails they are separated out.
6369 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)) {
6370 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6371 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6372 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6373 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6375 if send_funding_locked.0 {
6376 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6378 for reestablish in reestablish_1.iter() {
6379 assert_eq!(reestablish.next_remote_commitment_number, 0);
6382 if send_funding_locked.1 {
6383 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6385 for reestablish in reestablish_2.iter() {
6386 assert_eq!(reestablish.next_remote_commitment_number, 0);
6389 if send_funding_locked.0 || send_funding_locked.1 {
6390 // If we expect any funding_locked's, both sides better have set
6391 // next_local_commitment_number to 1
6392 for reestablish in reestablish_1.iter() {
6393 assert_eq!(reestablish.next_local_commitment_number, 1);
6395 for reestablish in reestablish_2.iter() {
6396 assert_eq!(reestablish.next_local_commitment_number, 1);
6400 let mut resp_1 = Vec::new();
6401 for msg in reestablish_1 {
6402 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6403 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6405 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6406 check_added_monitors!(node_b, 1);
6408 check_added_monitors!(node_b, 0);
6411 let mut resp_2 = Vec::new();
6412 for msg in reestablish_2 {
6413 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6414 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6416 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6417 check_added_monitors!(node_a, 1);
6419 check_added_monitors!(node_a, 0);
6422 // We dont yet support both needing updates, as that would require a different commitment dance:
6423 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
6424 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
6426 for chan_msgs in resp_1.drain(..) {
6427 if send_funding_locked.0 {
6428 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6429 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
6430 if !announcement_event.is_empty() {
6431 assert_eq!(announcement_event.len(), 1);
6432 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6433 //TODO: Test announcement_sigs re-sending
6434 } else { panic!("Unexpected event!"); }
6437 assert!(chan_msgs.0.is_none());
6440 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6441 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6442 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6443 check_added_monitors!(node_a, 1);
6445 assert!(chan_msgs.1.is_none());
6447 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6448 let commitment_update = chan_msgs.2.unwrap();
6449 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6450 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
6452 assert!(commitment_update.update_add_htlcs.is_empty());
6454 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6455 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6456 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6457 for update_add in commitment_update.update_add_htlcs {
6458 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
6460 for update_fulfill in commitment_update.update_fulfill_htlcs {
6461 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
6463 for update_fail in commitment_update.update_fail_htlcs {
6464 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
6467 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
6468 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
6470 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6471 check_added_monitors!(node_a, 1);
6472 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
6473 // No commitment_signed so get_event_msg's assert(len == 1) passes
6474 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6475 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6476 check_added_monitors!(node_b, 1);
6479 assert!(chan_msgs.2.is_none());
6483 for chan_msgs in resp_2.drain(..) {
6484 if send_funding_locked.1 {
6485 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6486 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
6487 if !announcement_event.is_empty() {
6488 assert_eq!(announcement_event.len(), 1);
6489 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
6490 //TODO: Test announcement_sigs re-sending
6491 } else { panic!("Unexpected event!"); }
6494 assert!(chan_msgs.0.is_none());
6497 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
6498 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
6499 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
6500 check_added_monitors!(node_b, 1);
6502 assert!(chan_msgs.1.is_none());
6504 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6505 let commitment_update = chan_msgs.2.unwrap();
6506 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6507 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
6509 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
6510 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
6511 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
6512 for update_add in commitment_update.update_add_htlcs {
6513 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
6515 for update_fulfill in commitment_update.update_fulfill_htlcs {
6516 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
6518 for update_fail in commitment_update.update_fail_htlcs {
6519 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
6522 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
6523 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
6525 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
6526 check_added_monitors!(node_b, 1);
6527 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
6528 // No commitment_signed so get_event_msg's assert(len == 1) passes
6529 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6530 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
6531 check_added_monitors!(node_a, 1);
6534 assert!(chan_msgs.2.is_none());
6540 fn test_simple_peer_disconnect() {
6541 // Test that we can reconnect when there are no lost messages
6542 let nodes = create_network(3);
6543 create_announced_chan_between_nodes(&nodes, 0, 1);
6544 create_announced_chan_between_nodes(&nodes, 1, 2);
6546 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6547 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6548 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6550 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6551 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6552 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
6553 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
6555 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6556 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6557 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6559 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6560 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
6561 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6562 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
6564 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6565 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6567 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
6568 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
6570 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
6572 let events = nodes[0].node.get_and_clear_pending_events();
6573 assert_eq!(events.len(), 2);
6575 Event::PaymentSent { payment_preimage } => {
6576 assert_eq!(payment_preimage, payment_preimage_3);
6578 _ => panic!("Unexpected event"),
6581 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
6582 assert_eq!(payment_hash, payment_hash_5);
6583 assert!(rejected_by_dest);
6585 _ => panic!("Unexpected event"),
6589 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
6590 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
6593 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
6594 // Test that we can reconnect when in-flight HTLC updates get dropped
6595 let mut nodes = create_network(2);
6596 if messages_delivered == 0 {
6597 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
6598 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
6600 create_announced_chan_between_nodes(&nodes, 0, 1);
6603 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();
6604 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6606 let payment_event = {
6607 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
6608 check_added_monitors!(nodes[0], 1);
6610 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6611 assert_eq!(events.len(), 1);
6612 SendEvent::from_event(events.remove(0))
6614 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
6616 if messages_delivered < 2 {
6617 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
6619 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6620 if messages_delivered >= 3 {
6621 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6622 check_added_monitors!(nodes[1], 1);
6623 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6625 if messages_delivered >= 4 {
6626 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6627 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6628 check_added_monitors!(nodes[0], 1);
6630 if messages_delivered >= 5 {
6631 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
6632 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6633 // No commitment_signed so get_event_msg's assert(len == 1) passes
6634 check_added_monitors!(nodes[0], 1);
6636 if messages_delivered >= 6 {
6637 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6638 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6639 check_added_monitors!(nodes[1], 1);
6646 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6647 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6648 if messages_delivered < 3 {
6649 // Even if the funding_locked messages get exchanged, as long as nothing further was
6650 // received on either side, both sides will need to resend them.
6651 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
6652 } else if messages_delivered == 3 {
6653 // nodes[0] still wants its RAA + commitment_signed
6654 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
6655 } else if messages_delivered == 4 {
6656 // nodes[0] still wants its commitment_signed
6657 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
6658 } else if messages_delivered == 5 {
6659 // nodes[1] still wants its final RAA
6660 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
6661 } else if messages_delivered == 6 {
6662 // Everything was delivered...
6663 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6666 let events_1 = nodes[1].node.get_and_clear_pending_events();
6667 assert_eq!(events_1.len(), 1);
6669 Event::PendingHTLCsForwardable { .. } => { },
6670 _ => panic!("Unexpected event"),
6673 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6674 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6675 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6677 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6678 nodes[1].node.process_pending_htlc_forwards();
6680 let events_2 = nodes[1].node.get_and_clear_pending_events();
6681 assert_eq!(events_2.len(), 1);
6683 Event::PaymentReceived { ref payment_hash, amt } => {
6684 assert_eq!(payment_hash_1, *payment_hash);
6685 assert_eq!(amt, 1000000);
6687 _ => panic!("Unexpected event"),
6690 nodes[1].node.claim_funds(payment_preimage_1);
6691 check_added_monitors!(nodes[1], 1);
6693 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
6694 assert_eq!(events_3.len(), 1);
6695 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
6696 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6697 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6698 assert!(updates.update_add_htlcs.is_empty());
6699 assert!(updates.update_fail_htlcs.is_empty());
6700 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6701 assert!(updates.update_fail_malformed_htlcs.is_empty());
6702 assert!(updates.update_fee.is_none());
6703 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
6705 _ => panic!("Unexpected event"),
6708 if messages_delivered >= 1 {
6709 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
6711 let events_4 = nodes[0].node.get_and_clear_pending_events();
6712 assert_eq!(events_4.len(), 1);
6714 Event::PaymentSent { ref payment_preimage } => {
6715 assert_eq!(payment_preimage_1, *payment_preimage);
6717 _ => panic!("Unexpected event"),
6720 if messages_delivered >= 2 {
6721 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
6722 check_added_monitors!(nodes[0], 1);
6723 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6725 if messages_delivered >= 3 {
6726 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6727 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6728 check_added_monitors!(nodes[1], 1);
6730 if messages_delivered >= 4 {
6731 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6732 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6733 // No commitment_signed so get_event_msg's assert(len == 1) passes
6734 check_added_monitors!(nodes[1], 1);
6736 if messages_delivered >= 5 {
6737 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6738 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6739 check_added_monitors!(nodes[0], 1);
6746 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6747 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6748 if messages_delivered < 2 {
6749 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
6750 //TODO: Deduplicate PaymentSent events, then enable this if:
6751 //if messages_delivered < 1 {
6752 let events_4 = nodes[0].node.get_and_clear_pending_events();
6753 assert_eq!(events_4.len(), 1);
6755 Event::PaymentSent { ref payment_preimage } => {
6756 assert_eq!(payment_preimage_1, *payment_preimage);
6758 _ => panic!("Unexpected event"),
6761 } else if messages_delivered == 2 {
6762 // nodes[0] still wants its RAA + commitment_signed
6763 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
6764 } else if messages_delivered == 3 {
6765 // nodes[0] still wants its commitment_signed
6766 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
6767 } else if messages_delivered == 4 {
6768 // nodes[1] still wants its final RAA
6769 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
6770 } else if messages_delivered == 5 {
6771 // Everything was delivered...
6772 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6775 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6776 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6777 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6779 // Channel should still work fine...
6780 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
6781 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
6785 fn test_drop_messages_peer_disconnect_a() {
6786 do_test_drop_messages_peer_disconnect(0);
6787 do_test_drop_messages_peer_disconnect(1);
6788 do_test_drop_messages_peer_disconnect(2);
6789 do_test_drop_messages_peer_disconnect(3);
6793 fn test_drop_messages_peer_disconnect_b() {
6794 do_test_drop_messages_peer_disconnect(4);
6795 do_test_drop_messages_peer_disconnect(5);
6796 do_test_drop_messages_peer_disconnect(6);
6800 fn test_funding_peer_disconnect() {
6801 // Test that we can lock in our funding tx while disconnected
6802 let nodes = create_network(2);
6803 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
6805 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6806 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6808 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
6809 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
6810 assert_eq!(events_1.len(), 1);
6812 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
6813 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6815 _ => panic!("Unexpected event"),
6818 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6820 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6821 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6823 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
6824 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6825 assert_eq!(events_2.len(), 2);
6827 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
6828 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6830 _ => panic!("Unexpected event"),
6833 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
6834 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6836 _ => panic!("Unexpected event"),
6839 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6841 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
6842 // rebroadcasting announcement_signatures upon reconnect.
6844 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();
6845 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
6846 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
6850 fn test_drop_messages_peer_disconnect_dual_htlc() {
6851 // Test that we can handle reconnecting when both sides of a channel have pending
6852 // commitment_updates when we disconnect.
6853 let mut nodes = create_network(2);
6854 create_announced_chan_between_nodes(&nodes, 0, 1);
6856 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6858 // Now try to send a second payment which will fail to send
6859 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6860 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6862 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
6863 check_added_monitors!(nodes[0], 1);
6865 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
6866 assert_eq!(events_1.len(), 1);
6868 MessageSendEvent::UpdateHTLCs { .. } => {},
6869 _ => panic!("Unexpected event"),
6872 assert!(nodes[1].node.claim_funds(payment_preimage_1));
6873 check_added_monitors!(nodes[1], 1);
6875 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6876 assert_eq!(events_2.len(), 1);
6878 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 } } => {
6879 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
6880 assert!(update_add_htlcs.is_empty());
6881 assert_eq!(update_fulfill_htlcs.len(), 1);
6882 assert!(update_fail_htlcs.is_empty());
6883 assert!(update_fail_malformed_htlcs.is_empty());
6884 assert!(update_fee.is_none());
6886 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
6887 let events_3 = nodes[0].node.get_and_clear_pending_events();
6888 assert_eq!(events_3.len(), 1);
6890 Event::PaymentSent { ref payment_preimage } => {
6891 assert_eq!(*payment_preimage, payment_preimage_1);
6893 _ => panic!("Unexpected event"),
6896 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6897 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6898 // No commitment_signed so get_event_msg's assert(len == 1) passes
6899 check_added_monitors!(nodes[0], 1);
6901 _ => panic!("Unexpected event"),
6904 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6905 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6907 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6908 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6909 assert_eq!(reestablish_1.len(), 1);
6910 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6911 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6912 assert_eq!(reestablish_2.len(), 1);
6914 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
6915 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6916 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
6917 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6919 assert!(as_resp.0.is_none());
6920 assert!(bs_resp.0.is_none());
6922 assert!(bs_resp.1.is_none());
6923 assert!(bs_resp.2.is_none());
6925 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
6927 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
6928 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
6929 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
6930 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
6931 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
6932 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();
6933 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
6934 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6935 // No commitment_signed so get_event_msg's assert(len == 1) passes
6936 check_added_monitors!(nodes[1], 1);
6938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
6939 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6940 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
6941 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
6942 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
6943 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
6944 assert!(bs_second_commitment_signed.update_fee.is_none());
6945 check_added_monitors!(nodes[1], 1);
6947 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6948 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6949 assert!(as_commitment_signed.update_add_htlcs.is_empty());
6950 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
6951 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
6952 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
6953 assert!(as_commitment_signed.update_fee.is_none());
6954 check_added_monitors!(nodes[0], 1);
6956 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
6957 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
6958 // No commitment_signed so get_event_msg's assert(len == 1) passes
6959 check_added_monitors!(nodes[0], 1);
6961 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
6962 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6963 // No commitment_signed so get_event_msg's assert(len == 1) passes
6964 check_added_monitors!(nodes[1], 1);
6966 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6967 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6968 check_added_monitors!(nodes[1], 1);
6970 let events_4 = nodes[1].node.get_and_clear_pending_events();
6971 assert_eq!(events_4.len(), 1);
6973 Event::PendingHTLCsForwardable { .. } => { },
6974 _ => panic!("Unexpected event"),
6977 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6978 nodes[1].node.process_pending_htlc_forwards();
6980 let events_5 = nodes[1].node.get_and_clear_pending_events();
6981 assert_eq!(events_5.len(), 1);
6983 Event::PaymentReceived { ref payment_hash, amt: _ } => {
6984 assert_eq!(payment_hash_2, *payment_hash);
6986 _ => panic!("Unexpected event"),
6989 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
6990 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6991 check_added_monitors!(nodes[0], 1);
6993 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
6997 fn test_simple_monitor_permanent_update_fail() {
6998 // Test that we handle a simple permanent monitor update failure
6999 let mut nodes = create_network(2);
7000 create_announced_chan_between_nodes(&nodes, 0, 1);
7002 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7003 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7005 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7006 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7007 check_added_monitors!(nodes[0], 1);
7009 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7010 assert_eq!(events_1.len(), 2);
7012 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7013 _ => panic!("Unexpected event"),
7016 MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7017 _ => panic!("Unexpected event"),
7020 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7021 // PaymentFailed event
7023 assert_eq!(nodes[0].node.list_channels().len(), 0);
7026 fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7027 // Test that we can recover from a simple temporary monitor update failure optionally with
7028 // a disconnect in between
7029 let mut nodes = create_network(2);
7030 create_announced_chan_between_nodes(&nodes, 0, 1);
7032 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7033 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7035 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7036 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7037 check_added_monitors!(nodes[0], 1);
7039 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7040 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7041 assert_eq!(nodes[0].node.list_channels().len(), 1);
7044 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7045 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7046 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7049 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7050 nodes[0].node.test_restore_channel_monitor();
7051 check_added_monitors!(nodes[0], 1);
7053 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7054 assert_eq!(events_2.len(), 1);
7055 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7056 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7057 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7058 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7060 expect_pending_htlcs_forwardable!(nodes[1]);
7062 let events_3 = nodes[1].node.get_and_clear_pending_events();
7063 assert_eq!(events_3.len(), 1);
7065 Event::PaymentReceived { ref payment_hash, amt } => {
7066 assert_eq!(payment_hash_1, *payment_hash);
7067 assert_eq!(amt, 1000000);
7069 _ => panic!("Unexpected event"),
7072 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7074 // Now set it to failed again...
7075 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7076 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7077 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7078 check_added_monitors!(nodes[0], 1);
7080 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7081 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7082 assert_eq!(nodes[0].node.list_channels().len(), 1);
7085 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7086 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7087 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7090 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7091 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7092 nodes[0].node.test_restore_channel_monitor();
7093 check_added_monitors!(nodes[0], 1);
7095 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7096 assert_eq!(events_5.len(), 1);
7098 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7099 _ => panic!("Unexpected event"),
7102 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7103 // PaymentFailed event
7105 assert_eq!(nodes[0].node.list_channels().len(), 0);
7109 fn test_simple_monitor_temporary_update_fail() {
7110 do_test_simple_monitor_temporary_update_fail(false);
7111 do_test_simple_monitor_temporary_update_fail(true);
7114 fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7115 let disconnect_flags = 8 | 16;
7117 // Test that we can recover from a temporary monitor update failure with some in-flight
7118 // HTLCs going on at the same time potentially with some disconnection thrown in.
7119 // * First we route a payment, then get a temporary monitor update failure when trying to
7120 // route a second payment. We then claim the first payment.
7121 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7122 // TemporaryFailure likely indicates net disconnect which resulted in failing to update
7123 // the ChannelMonitor on a watchtower).
7124 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7125 // immediately, otherwise we wait sconnect and deliver them via the reconnect
7126 // channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7127 // disconnect_count & !disconnect_flags is 0).
7128 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7129 // through message sending, potentially disconnect/reconnecting multiple times based on
7130 // disconnect_count, to get the update_fulfill_htlc through.
7131 // * We then walk through more message exchanges to get the original update_add_htlc
7132 // through, swapping message ordering based on disconnect_count & 8 and optionally
7133 // disconnect/reconnecting based on disconnect_count.
7134 let mut nodes = create_network(2);
7135 create_announced_chan_between_nodes(&nodes, 0, 1);
7137 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7139 // Now try to send a second payment which will fail to send
7140 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7141 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7143 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7144 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7145 check_added_monitors!(nodes[0], 1);
7147 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7148 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7149 assert_eq!(nodes[0].node.list_channels().len(), 1);
7151 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7152 // but nodes[0] won't respond since it is frozen.
7153 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7154 check_added_monitors!(nodes[1], 1);
7155 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7156 assert_eq!(events_2.len(), 1);
7157 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7158 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 } } => {
7159 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7160 assert!(update_add_htlcs.is_empty());
7161 assert_eq!(update_fulfill_htlcs.len(), 1);
7162 assert!(update_fail_htlcs.is_empty());
7163 assert!(update_fail_malformed_htlcs.is_empty());
7164 assert!(update_fee.is_none());
7166 if (disconnect_count & 16) == 0 {
7167 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7168 let events_3 = nodes[0].node.get_and_clear_pending_events();
7169 assert_eq!(events_3.len(), 1);
7171 Event::PaymentSent { ref payment_preimage } => {
7172 assert_eq!(*payment_preimage, payment_preimage_1);
7174 _ => panic!("Unexpected event"),
7177 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) {
7178 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7179 } else { panic!(); }
7182 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7184 _ => panic!("Unexpected event"),
7187 if disconnect_count & !disconnect_flags > 0 {
7188 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7189 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7192 // Now fix monitor updating...
7193 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7194 nodes[0].node.test_restore_channel_monitor();
7195 check_added_monitors!(nodes[0], 1);
7197 macro_rules! disconnect_reconnect_peers { () => { {
7198 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7199 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7201 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7202 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7203 assert_eq!(reestablish_1.len(), 1);
7204 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7205 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7206 assert_eq!(reestablish_2.len(), 1);
7208 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7209 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7210 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7211 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7213 assert!(as_resp.0.is_none());
7214 assert!(bs_resp.0.is_none());
7216 (reestablish_1, reestablish_2, as_resp, bs_resp)
7219 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7220 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7221 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7223 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7224 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7225 assert_eq!(reestablish_1.len(), 1);
7226 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7227 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7228 assert_eq!(reestablish_2.len(), 1);
7230 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7231 check_added_monitors!(nodes[0], 0);
7232 let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7233 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7234 check_added_monitors!(nodes[1], 0);
7235 let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7237 assert!(as_resp.0.is_none());
7238 assert!(bs_resp.0.is_none());
7240 assert!(bs_resp.1.is_none());
7241 if (disconnect_count & 16) == 0 {
7242 assert!(bs_resp.2.is_none());
7244 assert!(as_resp.1.is_some());
7245 assert!(as_resp.2.is_some());
7246 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7248 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7249 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7250 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7251 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7252 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7253 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7255 assert!(as_resp.1.is_none());
7257 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();
7258 let events_3 = nodes[0].node.get_and_clear_pending_events();
7259 assert_eq!(events_3.len(), 1);
7261 Event::PaymentSent { ref payment_preimage } => {
7262 assert_eq!(*payment_preimage, payment_preimage_1);
7264 _ => panic!("Unexpected event"),
7267 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7268 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7269 // No commitment_signed so get_event_msg's assert(len == 1) passes
7270 check_added_monitors!(nodes[0], 1);
7272 as_resp.1 = Some(as_resp_raa);
7276 if disconnect_count & !disconnect_flags > 1 {
7277 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7279 if (disconnect_count & 16) == 0 {
7280 assert!(reestablish_1 == second_reestablish_1);
7281 assert!(reestablish_2 == second_reestablish_2);
7283 assert!(as_resp == second_as_resp);
7284 assert!(bs_resp == second_bs_resp);
7287 (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7289 let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7290 assert_eq!(events_4.len(), 2);
7291 (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7292 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7293 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7296 _ => panic!("Unexpected event"),
7300 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7303 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7304 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7305 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7306 check_added_monitors!(nodes[1], 1);
7308 if disconnect_count & !disconnect_flags > 2 {
7309 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7311 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7312 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7314 assert!(as_resp.2.is_none());
7315 assert!(bs_resp.2.is_none());
7318 let as_commitment_update;
7319 let bs_second_commitment_update;
7321 macro_rules! handle_bs_raa { () => {
7322 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7323 as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7324 assert!(as_commitment_update.update_add_htlcs.is_empty());
7325 assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7326 assert!(as_commitment_update.update_fail_htlcs.is_empty());
7327 assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7328 assert!(as_commitment_update.update_fee.is_none());
7329 check_added_monitors!(nodes[0], 1);
7332 macro_rules! handle_initial_raa { () => {
7333 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7334 bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7335 assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7336 assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7337 assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7338 assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7339 assert!(bs_second_commitment_update.update_fee.is_none());
7340 check_added_monitors!(nodes[1], 1);
7343 if (disconnect_count & 8) == 0 {
7346 if disconnect_count & !disconnect_flags > 3 {
7347 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7349 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7350 assert!(bs_resp.1.is_none());
7352 assert!(as_resp.2.unwrap() == as_commitment_update);
7353 assert!(bs_resp.2.is_none());
7355 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7358 handle_initial_raa!();
7360 if disconnect_count & !disconnect_flags > 4 {
7361 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7363 assert!(as_resp.1.is_none());
7364 assert!(bs_resp.1.is_none());
7366 assert!(as_resp.2.unwrap() == as_commitment_update);
7367 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7370 handle_initial_raa!();
7372 if disconnect_count & !disconnect_flags > 3 {
7373 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7375 assert!(as_resp.1.is_none());
7376 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7378 assert!(as_resp.2.is_none());
7379 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7381 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7386 if disconnect_count & !disconnect_flags > 4 {
7387 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7389 assert!(as_resp.1.is_none());
7390 assert!(bs_resp.1.is_none());
7392 assert!(as_resp.2.unwrap() == as_commitment_update);
7393 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7397 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7398 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7399 // No commitment_signed so get_event_msg's assert(len == 1) passes
7400 check_added_monitors!(nodes[0], 1);
7402 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7403 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7404 // No commitment_signed so get_event_msg's assert(len == 1) passes
7405 check_added_monitors!(nodes[1], 1);
7407 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7408 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7409 check_added_monitors!(nodes[1], 1);
7411 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7412 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7413 check_added_monitors!(nodes[0], 1);
7415 expect_pending_htlcs_forwardable!(nodes[1]);
7417 let events_5 = nodes[1].node.get_and_clear_pending_events();
7418 assert_eq!(events_5.len(), 1);
7420 Event::PaymentReceived { ref payment_hash, amt } => {
7421 assert_eq!(payment_hash_2, *payment_hash);
7422 assert_eq!(amt, 1000000);
7424 _ => panic!("Unexpected event"),
7427 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7431 fn test_monitor_temporary_update_fail_a() {
7432 do_test_monitor_temporary_update_fail(0);
7433 do_test_monitor_temporary_update_fail(1);
7434 do_test_monitor_temporary_update_fail(2);
7435 do_test_monitor_temporary_update_fail(3);
7436 do_test_monitor_temporary_update_fail(4);
7437 do_test_monitor_temporary_update_fail(5);
7441 fn test_monitor_temporary_update_fail_b() {
7442 do_test_monitor_temporary_update_fail(2 | 8);
7443 do_test_monitor_temporary_update_fail(3 | 8);
7444 do_test_monitor_temporary_update_fail(4 | 8);
7445 do_test_monitor_temporary_update_fail(5 | 8);
7449 fn test_monitor_temporary_update_fail_c() {
7450 do_test_monitor_temporary_update_fail(1 | 16);
7451 do_test_monitor_temporary_update_fail(2 | 16);
7452 do_test_monitor_temporary_update_fail(3 | 16);
7453 do_test_monitor_temporary_update_fail(2 | 8 | 16);
7454 do_test_monitor_temporary_update_fail(3 | 8 | 16);
7458 fn test_invalid_channel_announcement() {
7459 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
7460 let secp_ctx = Secp256k1::new();
7461 let nodes = create_network(2);
7463 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
7465 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
7466 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
7467 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
7468 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
7470 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 } );
7472 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
7473 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
7475 let as_network_key = nodes[0].node.get_our_node_id();
7476 let bs_network_key = nodes[1].node.get_our_node_id();
7478 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
7480 let mut chan_announcement;
7482 macro_rules! dummy_unsigned_msg {
7484 msgs::UnsignedChannelAnnouncement {
7485 features: msgs::GlobalFeatures::new(),
7486 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
7487 short_channel_id: as_chan.get_short_channel_id().unwrap(),
7488 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
7489 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
7490 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
7491 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
7492 excess_data: Vec::new(),
7497 macro_rules! sign_msg {
7498 ($unsigned_msg: expr) => {
7499 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
7500 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
7501 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
7502 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
7503 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
7504 chan_announcement = msgs::ChannelAnnouncement {
7505 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
7506 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
7507 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
7508 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
7509 contents: $unsigned_msg
7514 let unsigned_msg = dummy_unsigned_msg!();
7515 sign_msg!(unsigned_msg);
7516 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
7517 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 } );
7519 // Configured with Network::Testnet
7520 let mut unsigned_msg = dummy_unsigned_msg!();
7521 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
7522 sign_msg!(unsigned_msg);
7523 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
7525 let mut unsigned_msg = dummy_unsigned_msg!();
7526 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
7527 sign_msg!(unsigned_msg);
7528 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
7531 struct VecWriter(Vec<u8>);
7532 impl Writer for VecWriter {
7533 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
7534 self.0.extend_from_slice(buf);
7537 fn size_hint(&mut self, size: usize) {
7538 self.0.reserve_exact(size);
7543 fn test_no_txn_manager_serialize_deserialize() {
7544 let mut nodes = create_network(2);
7546 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7548 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7550 let nodes_0_serialized = nodes[0].node.encode();
7551 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
7552 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
7554 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())));
7555 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
7556 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
7557 assert!(chan_0_monitor_read.is_empty());
7559 let mut nodes_0_read = &nodes_0_serialized[..];
7560 let config = UserConfig::new();
7561 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
7562 let (_, nodes_0_deserialized) = {
7563 let mut channel_monitors = HashMap::new();
7564 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
7565 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
7566 default_config: config,
7568 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
7569 monitor: nodes[0].chan_monitor.clone(),
7570 chain_monitor: nodes[0].chain_monitor.clone(),
7571 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
7572 logger: Arc::new(test_utils::TestLogger::new()),
7573 channel_monitors: &channel_monitors,
7576 assert!(nodes_0_read.is_empty());
7578 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
7579 nodes[0].node = Arc::new(nodes_0_deserialized);
7580 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
7581 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
7582 assert_eq!(nodes[0].node.list_channels().len(), 1);
7583 check_added_monitors!(nodes[0], 1);
7585 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7586 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7587 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7588 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7590 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7591 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7592 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7593 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7595 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
7596 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
7597 for node in nodes.iter() {
7598 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
7599 node.router.handle_channel_update(&as_update).unwrap();
7600 node.router.handle_channel_update(&bs_update).unwrap();
7603 send_payment(&nodes[0], &[&nodes[1]], 1000000);
7607 fn test_simple_manager_serialize_deserialize() {
7608 let mut nodes = create_network(2);
7609 create_announced_chan_between_nodes(&nodes, 0, 1);
7611 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7612 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7614 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7616 let nodes_0_serialized = nodes[0].node.encode();
7617 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
7618 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
7620 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())));
7621 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
7622 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
7623 assert!(chan_0_monitor_read.is_empty());
7625 let mut nodes_0_read = &nodes_0_serialized[..];
7626 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
7627 let (_, nodes_0_deserialized) = {
7628 let mut channel_monitors = HashMap::new();
7629 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
7630 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
7631 default_config: UserConfig::new(),
7633 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
7634 monitor: nodes[0].chan_monitor.clone(),
7635 chain_monitor: nodes[0].chain_monitor.clone(),
7636 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
7637 logger: Arc::new(test_utils::TestLogger::new()),
7638 channel_monitors: &channel_monitors,
7641 assert!(nodes_0_read.is_empty());
7643 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
7644 nodes[0].node = Arc::new(nodes_0_deserialized);
7645 check_added_monitors!(nodes[0], 1);
7647 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7649 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
7650 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
7654 fn test_manager_serialize_deserialize_inconsistent_monitor() {
7655 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
7656 let mut nodes = create_network(4);
7657 create_announced_chan_between_nodes(&nodes, 0, 1);
7658 create_announced_chan_between_nodes(&nodes, 2, 0);
7659 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
7661 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
7663 // Serialize the ChannelManager here, but the monitor we keep up-to-date
7664 let nodes_0_serialized = nodes[0].node.encode();
7666 route_payment(&nodes[0], &[&nodes[3]], 1000000);
7667 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7668 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7669 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7671 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
7673 let mut node_0_monitors_serialized = Vec::new();
7674 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
7675 let mut writer = VecWriter(Vec::new());
7676 monitor.1.write_for_disk(&mut writer).unwrap();
7677 node_0_monitors_serialized.push(writer.0);
7680 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())));
7681 let mut node_0_monitors = Vec::new();
7682 for serialized in node_0_monitors_serialized.iter() {
7683 let mut read = &serialized[..];
7684 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
7685 assert!(read.is_empty());
7686 node_0_monitors.push(monitor);
7689 let mut nodes_0_read = &nodes_0_serialized[..];
7690 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
7691 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
7692 default_config: UserConfig::new(),
7694 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
7695 monitor: nodes[0].chan_monitor.clone(),
7696 chain_monitor: nodes[0].chain_monitor.clone(),
7697 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
7698 logger: Arc::new(test_utils::TestLogger::new()),
7699 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
7701 assert!(nodes_0_read.is_empty());
7703 { // Channel close should result in a commitment tx and an HTLC tx
7704 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7705 assert_eq!(txn.len(), 2);
7706 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
7707 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
7710 for monitor in node_0_monitors.drain(..) {
7711 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
7712 check_added_monitors!(nodes[0], 1);
7714 nodes[0].node = Arc::new(nodes_0_deserialized);
7716 // nodes[1] and nodes[2] have no lost state with nodes[0]...
7717 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7718 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7719 //... and we can even still claim the payment!
7720 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
7722 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
7723 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7724 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
7725 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) {
7726 assert_eq!(msg.channel_id, channel_id);
7727 } else { panic!("Unexpected result"); }
7730 macro_rules! check_spendable_outputs {
7731 ($node: expr, $der_idx: expr) => {
7733 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
7734 let mut txn = Vec::new();
7735 for event in events {
7737 Event::SpendableOutputs { ref outputs } => {
7738 for outp in outputs {
7740 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
7742 previous_output: outpoint.clone(),
7743 script_sig: Script::new(),
7745 witness: Vec::new(),
7748 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
7749 value: output.value,
7751 let mut spend_tx = Transaction {
7757 let secp_ctx = Secp256k1::new();
7758 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
7759 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
7760 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
7761 let remotesig = secp_ctx.sign(&sighash, key);
7762 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
7763 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7764 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
7767 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
7769 previous_output: outpoint.clone(),
7770 script_sig: Script::new(),
7771 sequence: *to_self_delay as u32,
7772 witness: Vec::new(),
7775 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
7776 value: output.value,
7778 let mut spend_tx = Transaction {
7784 let secp_ctx = Secp256k1::new();
7785 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
7786 let local_delaysig = secp_ctx.sign(&sighash, key);
7787 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
7788 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7789 spend_tx.input[0].witness.push(vec!(0));
7790 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
7793 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
7794 let secp_ctx = Secp256k1::new();
7796 previous_output: outpoint.clone(),
7797 script_sig: Script::new(),
7799 witness: Vec::new(),
7802 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
7803 value: output.value,
7805 let mut spend_tx = Transaction {
7809 output: vec![outp.clone()],
7812 match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
7814 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
7816 Err(_) => panic!("Your RNG is busted"),
7819 Err(_) => panic!("Your rng is busted"),
7822 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
7823 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
7824 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
7825 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
7826 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
7827 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
7828 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
7834 _ => panic!("Unexpected event"),
7843 fn test_claim_sizeable_push_msat() {
7844 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
7845 let nodes = create_network(2);
7847 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
7848 nodes[1].node.force_close_channel(&chan.2);
7849 let events = nodes[1].node.get_and_clear_pending_msg_events();
7851 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7852 _ => panic!("Unexpected event"),
7854 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7855 assert_eq!(node_txn.len(), 1);
7856 check_spends!(node_txn[0], chan.3.clone());
7857 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
7859 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7860 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
7861 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7862 assert_eq!(spend_txn.len(), 1);
7863 check_spends!(spend_txn[0], node_txn[0].clone());
7867 fn test_claim_on_remote_sizeable_push_msat() {
7868 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
7869 // to_remote output is encumbered by a P2WPKH
7871 let nodes = create_network(2);
7873 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
7874 nodes[0].node.force_close_channel(&chan.2);
7875 let events = nodes[0].node.get_and_clear_pending_msg_events();
7877 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7878 _ => panic!("Unexpected event"),
7880 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7881 assert_eq!(node_txn.len(), 1);
7882 check_spends!(node_txn[0], chan.3.clone());
7883 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
7885 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7886 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
7887 let events = nodes[1].node.get_and_clear_pending_msg_events();
7889 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7890 _ => panic!("Unexpected event"),
7892 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7893 assert_eq!(spend_txn.len(), 2);
7894 assert_eq!(spend_txn[0], spend_txn[1]);
7895 check_spends!(spend_txn[0], node_txn[0].clone());
7899 fn test_claim_on_remote_revoked_sizeable_push_msat() {
7900 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
7901 // to_remote output is encumbered by a P2WPKH
7903 let nodes = create_network(2);
7905 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
7906 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7907 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
7908 assert_eq!(revoked_local_txn[0].input.len(), 1);
7909 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7911 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7912 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7913 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7914 let events = nodes[1].node.get_and_clear_pending_msg_events();
7916 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7917 _ => panic!("Unexpected event"),
7919 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7920 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7921 assert_eq!(spend_txn.len(), 4);
7922 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
7923 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
7924 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
7925 check_spends!(spend_txn[1], node_txn[0].clone());
7929 fn test_static_spendable_outputs_preimage_tx() {
7930 let nodes = create_network(2);
7932 // Create some initial channels
7933 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
7935 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7937 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
7938 assert_eq!(commitment_tx[0].input.len(), 1);
7939 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
7941 // Settle A's commitment tx on B's chain
7942 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7943 assert!(nodes[1].node.claim_funds(payment_preimage));
7944 check_added_monitors!(nodes[1], 1);
7945 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
7946 let events = nodes[1].node.get_and_clear_pending_msg_events();
7948 MessageSendEvent::UpdateHTLCs { .. } => {},
7949 _ => panic!("Unexpected event"),
7952 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7953 _ => panic!("Unexepected event"),
7956 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
7957 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
7958 check_spends!(node_txn[0], commitment_tx[0].clone());
7959 assert_eq!(node_txn[0], node_txn[2]);
7960 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
7961 check_spends!(node_txn[1], chan_1.3.clone());
7963 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
7964 assert_eq!(spend_txn.len(), 2);
7965 assert_eq!(spend_txn[0], spend_txn[1]);
7966 check_spends!(spend_txn[0], node_txn[0].clone());
7970 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
7971 let nodes = create_network(2);
7973 // Create some initial channels
7974 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
7976 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7977 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
7978 assert_eq!(revoked_local_txn[0].input.len(), 1);
7979 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
7981 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7983 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7984 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7985 let events = nodes[1].node.get_and_clear_pending_msg_events();
7987 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7988 _ => panic!("Unexpected event"),
7990 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7991 assert_eq!(node_txn.len(), 3);
7992 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
7993 assert_eq!(node_txn[0].input.len(), 2);
7994 check_spends!(node_txn[0], revoked_local_txn[0].clone());
7996 let spend_txn = check_spendable_outputs!(nodes[1], 1);
7997 assert_eq!(spend_txn.len(), 2);
7998 assert_eq!(spend_txn[0], spend_txn[1]);
7999 check_spends!(spend_txn[0], node_txn[0].clone());
8003 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
8004 let nodes = create_network(2);
8006 // Create some initial channels
8007 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8009 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8010 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8011 assert_eq!(revoked_local_txn[0].input.len(), 1);
8012 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8014 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8016 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8017 // A will generate HTLC-Timeout from revoked commitment tx
8018 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8019 let events = nodes[0].node.get_and_clear_pending_msg_events();
8021 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8022 _ => panic!("Unexpected event"),
8024 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8025 assert_eq!(revoked_htlc_txn.len(), 2);
8026 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8027 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 133);
8028 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8030 // B will generate justice tx from A's revoked commitment/HTLC tx
8031 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8032 let events = nodes[1].node.get_and_clear_pending_msg_events();
8034 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8035 _ => panic!("Unexpected event"),
8038 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8039 assert_eq!(node_txn.len(), 4);
8040 assert_eq!(node_txn[3].input.len(), 1);
8041 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8043 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
8044 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8045 assert_eq!(spend_txn.len(), 3);
8046 assert_eq!(spend_txn[0], spend_txn[1]);
8047 check_spends!(spend_txn[0], node_txn[0].clone());
8048 check_spends!(spend_txn[2], node_txn[3].clone());
8052 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
8053 let nodes = create_network(2);
8055 // Create some initial channels
8056 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8058 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8059 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8060 assert_eq!(revoked_local_txn[0].input.len(), 1);
8061 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8063 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8065 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8066 // B will generate HTLC-Success from revoked commitment tx
8067 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8068 let events = nodes[1].node.get_and_clear_pending_msg_events();
8070 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8071 _ => panic!("Unexpected event"),
8073 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8075 assert_eq!(revoked_htlc_txn.len(), 2);
8076 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8077 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), 138);
8078 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
8080 // A will generate justice tx from B's revoked commitment/HTLC tx
8081 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
8082 let events = nodes[0].node.get_and_clear_pending_msg_events();
8084 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8085 _ => panic!("Unexpected event"),
8088 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8089 assert_eq!(node_txn.len(), 4);
8090 assert_eq!(node_txn[3].input.len(), 1);
8091 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
8093 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
8094 let spend_txn = check_spendable_outputs!(nodes[0], 1);
8095 assert_eq!(spend_txn.len(), 5);
8096 assert_eq!(spend_txn[0], spend_txn[2]);
8097 assert_eq!(spend_txn[1], spend_txn[3]);
8098 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
8099 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
8100 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
8104 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
8105 let nodes = create_network(2);
8107 // Create some initial channels
8108 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8110 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8111 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8112 assert_eq!(local_txn[0].input.len(), 1);
8113 check_spends!(local_txn[0], chan_1.3.clone());
8115 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
8116 nodes[1].node.claim_funds(payment_preimage);
8117 check_added_monitors!(nodes[1], 1);
8118 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8119 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
8120 let events = nodes[1].node.get_and_clear_pending_msg_events();
8122 MessageSendEvent::UpdateHTLCs { .. } => {},
8123 _ => panic!("Unexpected event"),
8126 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8127 _ => panic!("Unexepected event"),
8129 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8130 assert_eq!(node_txn[0].input.len(), 1);
8131 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 138);
8132 check_spends!(node_txn[0], local_txn[0].clone());
8134 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
8135 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8136 assert_eq!(spend_txn.len(), 1);
8137 check_spends!(spend_txn[0], node_txn[0].clone());
8141 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
8142 let nodes = create_network(2);
8144 // Create some initial channels
8145 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8147 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
8148 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8149 assert_eq!(local_txn[0].input.len(), 1);
8150 check_spends!(local_txn[0], chan_1.3.clone());
8152 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8153 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8154 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8155 let events = nodes[0].node.get_and_clear_pending_msg_events();
8157 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8158 _ => panic!("Unexepected event"),
8160 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8161 assert_eq!(node_txn[0].input.len(), 1);
8162 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 133);
8163 check_spends!(node_txn[0], local_txn[0].clone());
8165 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
8166 let spend_txn = check_spendable_outputs!(nodes[0], 1);
8167 assert_eq!(spend_txn.len(), 4);
8168 assert_eq!(spend_txn[0], spend_txn[2]);
8169 assert_eq!(spend_txn[1], spend_txn[3]);
8170 check_spends!(spend_txn[0], local_txn[0].clone());
8171 check_spends!(spend_txn[1], node_txn[0].clone());
8175 fn test_static_output_closing_tx() {
8176 let nodes = create_network(2);
8178 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
8180 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
8181 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
8183 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8184 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
8185 let spend_txn = check_spendable_outputs!(nodes[0], 2);
8186 assert_eq!(spend_txn.len(), 1);
8187 check_spends!(spend_txn[0], closing_tx.clone());
8189 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
8190 let spend_txn = check_spendable_outputs!(nodes[1], 2);
8191 assert_eq!(spend_txn.len(), 1);
8192 check_spends!(spend_txn[0], closing_tx);