Merge pull request #2098 from tnull/2023-03-add-channel-pending-event
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::chain::keysinterface::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::block::{Block, BlockHeader};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::genesis_block;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
51
52 use regex;
53
54 use crate::io;
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex};
61
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
64
65 #[test]
66 fn test_insane_channel_opens() {
67         // Stand up a network of 2 nodes
68         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
69         let mut cfg = UserConfig::default();
70         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
71         let chanmon_cfgs = create_chanmon_cfgs(2);
72         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
73         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
74         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75
76         // Instantiate channel parameters where we push the maximum msats given our
77         // funding satoshis
78         let channel_value_sat = 31337; // same as funding satoshis
79         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
80         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81
82         // Have node0 initiate a channel to node1 with aforementioned parameters
83         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84
85         // Extract the channel open message from node0 to node1
86         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87
88         // Test helper that asserts we get the correct error string given a mutator
89         // that supposedly makes the channel open message insane
90         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
91                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
92                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
93                 assert_eq!(msg_events.len(), 1);
94                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
95                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96                         match action {
97                                 &ErrorAction::SendErrorMessage { .. } => {
98                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99                                 },
100                                 _ => panic!("unexpected event!"),
101                         }
102                 } else { assert!(false); }
103         };
104
105         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106
107         // Test all mutations that would make the channel open message insane
108         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
109         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110
111         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112
113         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114
115         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116
117         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118
119         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120
121         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122
123         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
124 }
125
126 #[test]
127 fn test_funding_exceeds_no_wumbo_limit() {
128         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129         // them.
130         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
131         let chanmon_cfgs = create_chanmon_cfgs(2);
132         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
133         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136
137         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
138                 Err(APIError::APIMisuseError { err }) => {
139                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
140                 },
141                 _ => panic!()
142         }
143 }
144
145 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
146         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
147         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
148         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
149         // in normal testing, we test it explicitly here.
150         let chanmon_cfgs = create_chanmon_cfgs(2);
151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
154         let default_config = UserConfig::default();
155
156         // Have node0 initiate a channel to node1 with aforementioned parameters
157         let mut push_amt = 100_000_000;
158         let feerate_per_kw = 253;
159         let opt_anchors = false;
160         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
161         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162
163         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
164         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
165         if !send_from_initiator {
166                 open_channel_message.channel_reserve_satoshis = 0;
167                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168         }
169         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170
171         // Extract the channel accept message from node1 to node0
172         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
173         if send_from_initiator {
174                 accept_channel_message.channel_reserve_satoshis = 0;
175                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176         }
177         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178         {
179                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
180                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
181                 let mut sender_node_per_peer_lock;
182                 let mut sender_node_peer_state_lock;
183                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
184                 chan.holder_selected_channel_reserve_satoshis = 0;
185                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
186         }
187
188         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
189         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
190         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191
192         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
193         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
194         if send_from_initiator {
195                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
196                         // Note that for outbound channels we have to consider the commitment tx fee and the
197                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
198                         // well as an additional HTLC.
199                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200         } else {
201                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
202         }
203 }
204
205 #[test]
206 fn test_counterparty_no_reserve() {
207         do_test_counterparty_no_reserve(true);
208         do_test_counterparty_no_reserve(false);
209 }
210
211 #[test]
212 fn test_async_inbound_update_fee() {
213         let chanmon_cfgs = create_chanmon_cfgs(2);
214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
216         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
217         create_announced_chan_between_nodes(&nodes, 0, 1);
218
219         // balancing
220         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
221
222         // A                                        B
223         // update_fee                            ->
224         // send (1) commitment_signed            -.
225         //                                       <- update_add_htlc/commitment_signed
226         // send (2) RAA (awaiting remote revoke) -.
227         // (1) commitment_signed is delivered    ->
228         //                                       .- send (3) RAA (awaiting remote revoke)
229         // (2) RAA is delivered                  ->
230         //                                       .- send (4) commitment_signed
231         //                                       <- (3) RAA is delivered
232         // send (5) commitment_signed            -.
233         //                                       <- (4) commitment_signed is delivered
234         // send (6) RAA                          -.
235         // (5) commitment_signed is delivered    ->
236         //                                       <- RAA
237         // (6) RAA is delivered                  ->
238
239         // First nodes[0] generates an update_fee
240         {
241                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
242                 *feerate_lock += 20;
243         }
244         nodes[0].node.timer_tick_occurred();
245         check_added_monitors!(nodes[0], 1);
246
247         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
248         assert_eq!(events_0.len(), 1);
249         let (update_msg, commitment_signed) = match events_0[0] { // (1)
250                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
251                         (update_fee.as_ref(), commitment_signed)
252                 },
253                 _ => panic!("Unexpected event"),
254         };
255
256         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257
258         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
259         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
260         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         // deliver(1), generate (3):
279         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[1], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290         assert!(bs_update.update_fee.is_none()); // (4)
291         check_added_monitors!(nodes[1], 1);
292
293         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295         assert!(as_update.update_add_htlcs.is_empty()); // (5)
296         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299         assert!(as_update.update_fee.is_none()); // (5)
300         check_added_monitors!(nodes[0], 1);
301
302         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304         // only (6) so get_event_msg's assert(len == 1) passes
305         check_added_monitors!(nodes[0], 1);
306
307         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309         check_added_monitors!(nodes[1], 1);
310
311         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312         check_added_monitors!(nodes[0], 1);
313
314         let events_2 = nodes[0].node.get_and_clear_pending_events();
315         assert_eq!(events_2.len(), 1);
316         match events_2[0] {
317                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318                 _ => panic!("Unexpected event"),
319         }
320
321         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322         check_added_monitors!(nodes[1], 1);
323 }
324
325 #[test]
326 fn test_update_fee_unordered_raa() {
327         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328         // crash in an earlier version of the update_fee patch)
329         let chanmon_cfgs = create_chanmon_cfgs(2);
330         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333         create_announced_chan_between_nodes(&nodes, 0, 1);
334
335         // balancing
336         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
337
338         // First nodes[0] generates an update_fee
339         {
340                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
341                 *feerate_lock += 20;
342         }
343         nodes[0].node.timer_tick_occurred();
344         check_added_monitors!(nodes[0], 1);
345
346         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347         assert_eq!(events_0.len(), 1);
348         let update_msg = match events_0[0] { // (1)
349                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
350                         update_fee.as_ref()
351                 },
352                 _ => panic!("Unexpected event"),
353         };
354
355         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
356
357         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
360         check_added_monitors!(nodes[1], 1);
361
362         let payment_event = {
363                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
364                 assert_eq!(events_1.len(), 1);
365                 SendEvent::from_event(events_1.remove(0))
366         };
367         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
368         assert_eq!(payment_event.msgs.len(), 1);
369
370         // ...now when the messages get delivered everyone should be happy
371         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
372         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
373         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
374         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
375         check_added_monitors!(nodes[0], 1);
376
377         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
378         check_added_monitors!(nodes[1], 1);
379
380         // We can't continue, sadly, because our (1) now has a bogus signature
381 }
382
383 #[test]
384 fn test_multi_flight_update_fee() {
385         let chanmon_cfgs = create_chanmon_cfgs(2);
386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
389         create_announced_chan_between_nodes(&nodes, 0, 1);
390
391         // A                                        B
392         // update_fee/commitment_signed          ->
393         //                                       .- send (1) RAA and (2) commitment_signed
394         // update_fee (never committed)          ->
395         // (3) update_fee                        ->
396         // We have to manually generate the above update_fee, it is allowed by the protocol but we
397         // don't track which updates correspond to which revoke_and_ack responses so we're in
398         // AwaitingRAA mode and will not generate the update_fee yet.
399         //                                       <- (1) RAA delivered
400         // (3) is generated and send (4) CS      -.
401         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
402         // know the per_commitment_point to use for it.
403         //                                       <- (2) commitment_signed delivered
404         // revoke_and_ack                        ->
405         //                                          B should send no response here
406         // (4) commitment_signed delivered       ->
407         //                                       <- RAA/commitment_signed delivered
408         // revoke_and_ack                        ->
409
410         // First nodes[0] generates an update_fee
411         let initial_feerate;
412         {
413                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
414                 initial_feerate = *feerate_lock;
415                 *feerate_lock = initial_feerate + 20;
416         }
417         nodes[0].node.timer_tick_occurred();
418         check_added_monitors!(nodes[0], 1);
419
420         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
421         assert_eq!(events_0.len(), 1);
422         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
423                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
424                         (update_fee.as_ref().unwrap(), commitment_signed)
425                 },
426                 _ => panic!("Unexpected event"),
427         };
428
429         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
430         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
431         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
432         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
433         check_added_monitors!(nodes[1], 1);
434
435         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
436         // transaction:
437         {
438                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
439                 *feerate_lock = initial_feerate + 40;
440         }
441         nodes[0].node.timer_tick_occurred();
442         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
443         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
444
445         // Create the (3) update_fee message that nodes[0] will generate before it does...
446         let mut update_msg_2 = msgs::UpdateFee {
447                 channel_id: update_msg_1.channel_id.clone(),
448                 feerate_per_kw: (initial_feerate + 30) as u32,
449         };
450
451         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452
453         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
454         // Deliver (3)
455         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
456
457         // Deliver (1), generating (3) and (4)
458         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
459         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
460         check_added_monitors!(nodes[0], 1);
461         assert!(as_second_update.update_add_htlcs.is_empty());
462         assert!(as_second_update.update_fulfill_htlcs.is_empty());
463         assert!(as_second_update.update_fail_htlcs.is_empty());
464         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
465         // Check that the update_fee newly generated matches what we delivered:
466         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
467         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
468
469         // Deliver (2) commitment_signed
470         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
471         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
472         check_added_monitors!(nodes[0], 1);
473         // No commitment_signed so get_event_msg's assert(len == 1) passes
474
475         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
476         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
477         check_added_monitors!(nodes[1], 1);
478
479         // Delever (4)
480         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
481         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
482         check_added_monitors!(nodes[1], 1);
483
484         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
485         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
486         check_added_monitors!(nodes[0], 1);
487
488         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
489         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
490         // No commitment_signed so get_event_msg's assert(len == 1) passes
491         check_added_monitors!(nodes[0], 1);
492
493         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
494         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
495         check_added_monitors!(nodes[1], 1);
496 }
497
498 fn do_test_sanity_on_in_flight_opens(steps: u8) {
499         // Previously, we had issues deserializing channels when we hadn't connected the first block
500         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
501         // serialization round-trips and simply do steps towards opening a channel and then drop the
502         // Node objects.
503
504         let chanmon_cfgs = create_chanmon_cfgs(2);
505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
507         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
508
509         if steps & 0b1000_0000 != 0{
510                 let block = Block {
511                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
512                         txdata: vec![],
513                 };
514                 connect_block(&nodes[0], &block);
515                 connect_block(&nodes[1], &block);
516         }
517
518         if steps & 0x0f == 0 { return; }
519         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
520         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
521
522         if steps & 0x0f == 1 { return; }
523         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
524         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
525
526         if steps & 0x0f == 2 { return; }
527         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
528
529         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
530
531         if steps & 0x0f == 3 { return; }
532         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
533         check_added_monitors!(nodes[0], 0);
534         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
535
536         if steps & 0x0f == 4 { return; }
537         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
538         {
539                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
540                 assert_eq!(added_monitors.len(), 1);
541                 assert_eq!(added_monitors[0].0, funding_output);
542                 added_monitors.clear();
543         }
544         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
545
546         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
547
548         if steps & 0x0f == 5 { return; }
549         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
550         {
551                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
552                 assert_eq!(added_monitors.len(), 1);
553                 assert_eq!(added_monitors[0].0, funding_output);
554                 added_monitors.clear();
555         }
556
557         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
558         let events_4 = nodes[0].node.get_and_clear_pending_events();
559         assert_eq!(events_4.len(), 0);
560
561         if steps & 0x0f == 6 { return; }
562         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
563
564         if steps & 0x0f == 7 { return; }
565         confirm_transaction_at(&nodes[0], &tx, 2);
566         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
567         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
568         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
569 }
570
571 #[test]
572 fn test_sanity_on_in_flight_opens() {
573         do_test_sanity_on_in_flight_opens(0);
574         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(1);
576         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(2);
578         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(3);
580         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(4);
582         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(5);
584         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(6);
586         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(7);
588         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(8);
590         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
591 }
592
593 #[test]
594 fn test_update_fee_vanilla() {
595         let chanmon_cfgs = create_chanmon_cfgs(2);
596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
598         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
599         create_announced_chan_between_nodes(&nodes, 0, 1);
600
601         {
602                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
603                 *feerate_lock += 25;
604         }
605         nodes[0].node.timer_tick_occurred();
606         check_added_monitors!(nodes[0], 1);
607
608         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
609         assert_eq!(events_0.len(), 1);
610         let (update_msg, commitment_signed) = match events_0[0] {
611                         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 } } => {
612                         (update_fee.as_ref(), commitment_signed)
613                 },
614                 _ => panic!("Unexpected event"),
615         };
616         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
617
618         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
619         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
620         check_added_monitors!(nodes[1], 1);
621
622         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
623         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
624         check_added_monitors!(nodes[0], 1);
625
626         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
627         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
628         // No commitment_signed so get_event_msg's assert(len == 1) passes
629         check_added_monitors!(nodes[0], 1);
630
631         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
632         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
633         check_added_monitors!(nodes[1], 1);
634 }
635
636 #[test]
637 fn test_update_fee_that_funder_cannot_afford() {
638         let chanmon_cfgs = create_chanmon_cfgs(2);
639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
641         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
642         let channel_value = 5000;
643         let push_sats = 700;
644         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
645         let channel_id = chan.2;
646         let secp_ctx = Secp256k1::new();
647         let default_config = UserConfig::default();
648         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
649
650         let opt_anchors = false;
651
652         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
653         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
654         // calculate two different feerates here - the expected local limit as well as the expected
655         // remote limit.
656         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
657         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
658         {
659                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
660                 *feerate_lock = feerate;
661         }
662         nodes[0].node.timer_tick_occurred();
663         check_added_monitors!(nodes[0], 1);
664         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
665
666         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
667
668         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
669
670         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
671         {
672                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
673
674                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
675                 assert_eq!(commitment_tx.output.len(), 2);
676                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
677                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
678                 actual_fee = channel_value - actual_fee;
679                 assert_eq!(total_fee, actual_fee);
680         }
681
682         {
683                 // Increment the feerate by a small constant, accounting for rounding errors
684                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
685                 *feerate_lock += 4;
686         }
687         nodes[0].node.timer_tick_occurred();
688         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
689         check_added_monitors!(nodes[0], 0);
690
691         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
692
693         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
694         // needed to sign the new commitment tx and (2) sign the new commitment tx.
695         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
696                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
697                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
698                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
699                 let chan_signer = local_chan.get_signer();
700                 let pubkeys = chan_signer.pubkeys();
701                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
702                  pubkeys.funding_pubkey)
703         };
704         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
705                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
706                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
707                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
708                 let chan_signer = remote_chan.get_signer();
709                 let pubkeys = chan_signer.pubkeys();
710                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
711                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
712                  pubkeys.funding_pubkey)
713         };
714
715         // Assemble the set of keys we can use for signatures for our commitment_signed message.
716         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
717                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
718
719         let res = {
720                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
721                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
722                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
723                 let local_chan_signer = local_chan.get_signer();
724                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
725                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
726                         INITIAL_COMMITMENT_NUMBER - 1,
727                         push_sats,
728                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
729                         opt_anchors, local_funding, remote_funding,
730                         commit_tx_keys.clone(),
731                         non_buffer_feerate + 4,
732                         &mut htlcs,
733                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
734                 );
735                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
736         };
737
738         let commit_signed_msg = msgs::CommitmentSigned {
739                 channel_id: chan.2,
740                 signature: res.0,
741                 htlc_signatures: res.1
742         };
743
744         let update_fee = msgs::UpdateFee {
745                 channel_id: chan.2,
746                 feerate_per_kw: non_buffer_feerate + 4,
747         };
748
749         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
750
751         //While producing the commitment_signed response after handling a received update_fee request the
752         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753         //Should produce and error.
754         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756         check_added_monitors!(nodes[1], 1);
757         check_closed_broadcast!(nodes[1], true);
758         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
759 }
760
761 #[test]
762 fn test_update_fee_with_fundee_update_add_htlc() {
763         let chanmon_cfgs = create_chanmon_cfgs(2);
764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
768
769         // balancing
770         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
771
772         {
773                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
774                 *feerate_lock += 20;
775         }
776         nodes[0].node.timer_tick_occurred();
777         check_added_monitors!(nodes[0], 1);
778
779         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780         assert_eq!(events_0.len(), 1);
781         let (update_msg, commitment_signed) = match events_0[0] {
782                         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 } } => {
783                         (update_fee.as_ref(), commitment_signed)
784                 },
785                 _ => panic!("Unexpected event"),
786         };
787         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790         check_added_monitors!(nodes[1], 1);
791
792         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
793
794         // nothing happens since node[1] is in AwaitingRemoteRevoke
795         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
796         {
797                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
798                 assert_eq!(added_monitors.len(), 0);
799                 added_monitors.clear();
800         }
801         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
802         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
803         // node[1] has nothing to do
804
805         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
806         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
807         check_added_monitors!(nodes[0], 1);
808
809         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
810         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
811         // No commitment_signed so get_event_msg's assert(len == 1) passes
812         check_added_monitors!(nodes[0], 1);
813         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
814         check_added_monitors!(nodes[1], 1);
815         // AwaitingRemoteRevoke ends here
816
817         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
818         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
819         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
820         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
821         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
822         assert_eq!(commitment_update.update_fee.is_none(), true);
823
824         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
825         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
826         check_added_monitors!(nodes[0], 1);
827         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
828
829         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
830         check_added_monitors!(nodes[1], 1);
831         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
832
833         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
834         check_added_monitors!(nodes[1], 1);
835         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
836         // No commitment_signed so get_event_msg's assert(len == 1) passes
837
838         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
839         check_added_monitors!(nodes[0], 1);
840         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
841
842         expect_pending_htlcs_forwardable!(nodes[0]);
843
844         let events = nodes[0].node.get_and_clear_pending_events();
845         assert_eq!(events.len(), 1);
846         match events[0] {
847                 Event::PaymentClaimable { .. } => { },
848                 _ => panic!("Unexpected event"),
849         };
850
851         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
852
853         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
854         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
855         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
856         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
857         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
858 }
859
860 #[test]
861 fn test_update_fee() {
862         let chanmon_cfgs = create_chanmon_cfgs(2);
863         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
864         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
865         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
866         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
867         let channel_id = chan.2;
868
869         // A                                        B
870         // (1) update_fee/commitment_signed      ->
871         //                                       <- (2) revoke_and_ack
872         //                                       .- send (3) commitment_signed
873         // (4) update_fee/commitment_signed      ->
874         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
875         //                                       <- (3) commitment_signed delivered
876         // send (6) revoke_and_ack               -.
877         //                                       <- (5) deliver revoke_and_ack
878         // (6) deliver revoke_and_ack            ->
879         //                                       .- send (7) commitment_signed in response to (4)
880         //                                       <- (7) deliver commitment_signed
881         // revoke_and_ack                        ->
882
883         // Create and deliver (1)...
884         let feerate;
885         {
886                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
887                 feerate = *feerate_lock;
888                 *feerate_lock = feerate + 20;
889         }
890         nodes[0].node.timer_tick_occurred();
891         check_added_monitors!(nodes[0], 1);
892
893         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
894         assert_eq!(events_0.len(), 1);
895         let (update_msg, commitment_signed) = match events_0[0] {
896                         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 } } => {
897                         (update_fee.as_ref(), commitment_signed)
898                 },
899                 _ => panic!("Unexpected event"),
900         };
901         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
902
903         // Generate (2) and (3):
904         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
905         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
906         check_added_monitors!(nodes[1], 1);
907
908         // Deliver (2):
909         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
910         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
911         check_added_monitors!(nodes[0], 1);
912
913         // Create and deliver (4)...
914         {
915                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
916                 *feerate_lock = feerate + 30;
917         }
918         nodes[0].node.timer_tick_occurred();
919         check_added_monitors!(nodes[0], 1);
920         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
921         assert_eq!(events_0.len(), 1);
922         let (update_msg, commitment_signed) = match events_0[0] {
923                         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 } } => {
924                         (update_fee.as_ref(), commitment_signed)
925                 },
926                 _ => panic!("Unexpected event"),
927         };
928
929         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
930         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
931         check_added_monitors!(nodes[1], 1);
932         // ... creating (5)
933         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
934         // No commitment_signed so get_event_msg's assert(len == 1) passes
935
936         // Handle (3), creating (6):
937         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
938         check_added_monitors!(nodes[0], 1);
939         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
940         // No commitment_signed so get_event_msg's assert(len == 1) passes
941
942         // Deliver (5):
943         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
944         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
945         check_added_monitors!(nodes[0], 1);
946
947         // Deliver (6), creating (7):
948         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
949         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
950         assert!(commitment_update.update_add_htlcs.is_empty());
951         assert!(commitment_update.update_fulfill_htlcs.is_empty());
952         assert!(commitment_update.update_fail_htlcs.is_empty());
953         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
954         assert!(commitment_update.update_fee.is_none());
955         check_added_monitors!(nodes[1], 1);
956
957         // Deliver (7)
958         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
959         check_added_monitors!(nodes[0], 1);
960         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
961         // No commitment_signed so get_event_msg's assert(len == 1) passes
962
963         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
964         check_added_monitors!(nodes[1], 1);
965         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
966
967         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
968         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
969         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
970         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
971         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
972 }
973
974 #[test]
975 fn fake_network_test() {
976         // Simple test which builds a network of ChannelManagers, connects them to each other, and
977         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
978         let chanmon_cfgs = create_chanmon_cfgs(4);
979         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
980         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
981         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
982
983         // Create some initial channels
984         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
985         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
986         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
987
988         // Rebalance the network a bit by relaying one payment through all the channels...
989         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
990         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993
994         // Send some more payments
995         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
996         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
997         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
998
999         // Test failure packets
1000         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1001         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1002
1003         // Add a new channel that skips 3
1004         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1005
1006         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1007         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1008         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1009         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013
1014         // Do some rebalance loop payments, simultaneously
1015         let mut hops = Vec::with_capacity(3);
1016         hops.push(RouteHop {
1017                 pubkey: nodes[2].node.get_our_node_id(),
1018                 node_features: NodeFeatures::empty(),
1019                 short_channel_id: chan_2.0.contents.short_channel_id,
1020                 channel_features: ChannelFeatures::empty(),
1021                 fee_msat: 0,
1022                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1023         });
1024         hops.push(RouteHop {
1025                 pubkey: nodes[3].node.get_our_node_id(),
1026                 node_features: NodeFeatures::empty(),
1027                 short_channel_id: chan_3.0.contents.short_channel_id,
1028                 channel_features: ChannelFeatures::empty(),
1029                 fee_msat: 0,
1030                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1031         });
1032         hops.push(RouteHop {
1033                 pubkey: nodes[1].node.get_our_node_id(),
1034                 node_features: nodes[1].node.node_features(),
1035                 short_channel_id: chan_4.0.contents.short_channel_id,
1036                 channel_features: nodes[1].node.channel_features(),
1037                 fee_msat: 1000000,
1038                 cltv_expiry_delta: TEST_FINAL_CLTV,
1039         });
1040         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;
1041         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;
1042         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1043
1044         let mut hops = Vec::with_capacity(3);
1045         hops.push(RouteHop {
1046                 pubkey: nodes[3].node.get_our_node_id(),
1047                 node_features: NodeFeatures::empty(),
1048                 short_channel_id: chan_4.0.contents.short_channel_id,
1049                 channel_features: ChannelFeatures::empty(),
1050                 fee_msat: 0,
1051                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1052         });
1053         hops.push(RouteHop {
1054                 pubkey: nodes[2].node.get_our_node_id(),
1055                 node_features: NodeFeatures::empty(),
1056                 short_channel_id: chan_3.0.contents.short_channel_id,
1057                 channel_features: ChannelFeatures::empty(),
1058                 fee_msat: 0,
1059                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1060         });
1061         hops.push(RouteHop {
1062                 pubkey: nodes[1].node.get_our_node_id(),
1063                 node_features: nodes[1].node.node_features(),
1064                 short_channel_id: chan_2.0.contents.short_channel_id,
1065                 channel_features: nodes[1].node.channel_features(),
1066                 fee_msat: 1000000,
1067                 cltv_expiry_delta: TEST_FINAL_CLTV,
1068         });
1069         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;
1070         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;
1071         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1072
1073         // Claim the rebalances...
1074         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1075         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1076
1077         // Close down the channels...
1078         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1079         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1080         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1081         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1082         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1083         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1084         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1085         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1086         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1087         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1088         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1089         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1090 }
1091
1092 #[test]
1093 fn holding_cell_htlc_counting() {
1094         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1095         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1096         // commitment dance rounds.
1097         let chanmon_cfgs = create_chanmon_cfgs(3);
1098         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1099         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1100         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1101         create_announced_chan_between_nodes(&nodes, 0, 1);
1102         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1103
1104         let mut payments = Vec::new();
1105         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1106                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1107                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1108                 payments.push((payment_preimage, payment_hash));
1109         }
1110         check_added_monitors!(nodes[1], 1);
1111
1112         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1113         assert_eq!(events.len(), 1);
1114         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1115         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1116
1117         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1118         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1119         // another HTLC.
1120         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1121         {
1122                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)), true, APIError::ChannelUnavailable { ref err },
1123                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1124                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1125                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1126         }
1127
1128         // This should also be true if we try to forward a payment.
1129         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1130         {
1131                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1132                 check_added_monitors!(nodes[0], 1);
1133         }
1134
1135         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1136         assert_eq!(events.len(), 1);
1137         let payment_event = SendEvent::from_event(events.pop().unwrap());
1138         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1139
1140         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1141         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1142         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1143         // fails), the second will process the resulting failure and fail the HTLC backward.
1144         expect_pending_htlcs_forwardable!(nodes[1]);
1145         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1146         check_added_monitors!(nodes[1], 1);
1147
1148         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1149         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1150         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1151
1152         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1153
1154         // Now forward all the pending HTLCs and claim them back
1155         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1156         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1157         check_added_monitors!(nodes[2], 1);
1158
1159         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1160         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1161         check_added_monitors!(nodes[1], 1);
1162         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1163
1164         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1165         check_added_monitors!(nodes[1], 1);
1166         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1167
1168         for ref update in as_updates.update_add_htlcs.iter() {
1169                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1170         }
1171         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1172         check_added_monitors!(nodes[2], 1);
1173         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1174         check_added_monitors!(nodes[2], 1);
1175         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1176
1177         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1178         check_added_monitors!(nodes[1], 1);
1179         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1180         check_added_monitors!(nodes[1], 1);
1181         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1182
1183         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1184         check_added_monitors!(nodes[2], 1);
1185
1186         expect_pending_htlcs_forwardable!(nodes[2]);
1187
1188         let events = nodes[2].node.get_and_clear_pending_events();
1189         assert_eq!(events.len(), payments.len());
1190         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1191                 match event {
1192                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1193                                 assert_eq!(*payment_hash, *hash);
1194                         },
1195                         _ => panic!("Unexpected event"),
1196                 };
1197         }
1198
1199         for (preimage, _) in payments.drain(..) {
1200                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1201         }
1202
1203         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1204 }
1205
1206 #[test]
1207 fn duplicate_htlc_test() {
1208         // Test that we accept duplicate payment_hash HTLCs across the network and that
1209         // claiming/failing them are all separate and don't affect each other
1210         let chanmon_cfgs = create_chanmon_cfgs(6);
1211         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1212         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1213         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1214
1215         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1216         create_announced_chan_between_nodes(&nodes, 0, 3);
1217         create_announced_chan_between_nodes(&nodes, 1, 3);
1218         create_announced_chan_between_nodes(&nodes, 2, 3);
1219         create_announced_chan_between_nodes(&nodes, 3, 4);
1220         create_announced_chan_between_nodes(&nodes, 3, 5);
1221
1222         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1223
1224         *nodes[0].network_payment_count.borrow_mut() -= 1;
1225         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1226
1227         *nodes[0].network_payment_count.borrow_mut() -= 1;
1228         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1229
1230         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1231         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1232         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1233 }
1234
1235 #[test]
1236 fn test_duplicate_htlc_different_direction_onchain() {
1237         // Test that ChannelMonitor doesn't generate 2 preimage txn
1238         // when we have 2 HTLCs with same preimage that go across a node
1239         // in opposite directions, even with the same payment secret.
1240         let chanmon_cfgs = create_chanmon_cfgs(2);
1241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1243         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1244
1245         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1246
1247         // balancing
1248         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1249
1250         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1251
1252         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1253         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1254         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1255
1256         // Provide preimage to node 0 by claiming payment
1257         nodes[0].node.claim_funds(payment_preimage);
1258         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1259         check_added_monitors!(nodes[0], 1);
1260
1261         // Broadcast node 1 commitment txn
1262         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1263
1264         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1265         let mut has_both_htlcs = 0; // check htlcs match ones committed
1266         for outp in remote_txn[0].output.iter() {
1267                 if outp.value == 800_000 / 1000 {
1268                         has_both_htlcs += 1;
1269                 } else if outp.value == 900_000 / 1000 {
1270                         has_both_htlcs += 1;
1271                 }
1272         }
1273         assert_eq!(has_both_htlcs, 2);
1274
1275         mine_transaction(&nodes[0], &remote_txn[0]);
1276         check_added_monitors!(nodes[0], 1);
1277         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1278         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1279
1280         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1281         assert_eq!(claim_txn.len(), 3);
1282
1283         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1284         check_spends!(claim_txn[1], remote_txn[0]);
1285         check_spends!(claim_txn[2], remote_txn[0]);
1286         let preimage_tx = &claim_txn[0];
1287         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1288                 (&claim_txn[1], &claim_txn[2])
1289         } else {
1290                 (&claim_txn[2], &claim_txn[1])
1291         };
1292
1293         assert_eq!(preimage_tx.input.len(), 1);
1294         assert_eq!(preimage_bump_tx.input.len(), 1);
1295
1296         assert_eq!(preimage_tx.input.len(), 1);
1297         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1298         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1299
1300         assert_eq!(timeout_tx.input.len(), 1);
1301         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1302         check_spends!(timeout_tx, remote_txn[0]);
1303         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1304
1305         let events = nodes[0].node.get_and_clear_pending_msg_events();
1306         assert_eq!(events.len(), 3);
1307         for e in events {
1308                 match e {
1309                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1310                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1311                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1312                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1313                         },
1314                         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, .. } } => {
1315                                 assert!(update_add_htlcs.is_empty());
1316                                 assert!(update_fail_htlcs.is_empty());
1317                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1318                                 assert!(update_fail_malformed_htlcs.is_empty());
1319                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1320                         },
1321                         _ => panic!("Unexpected event"),
1322                 }
1323         }
1324 }
1325
1326 #[test]
1327 fn test_basic_channel_reserve() {
1328         let chanmon_cfgs = create_chanmon_cfgs(2);
1329         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1330         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1331         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1332         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1333
1334         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1335         let channel_reserve = chan_stat.channel_reserve_msat;
1336
1337         // The 2* and +1 are for the fee spike reserve.
1338         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1339         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1340         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1341         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1342         match err {
1343                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1344                         match &fails[0] {
1345                                 &APIError::ChannelUnavailable{ref err} =>
1346                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1347                                 _ => panic!("Unexpected error variant"),
1348                         }
1349                 },
1350                 _ => panic!("Unexpected error variant"),
1351         }
1352         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1353         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1354
1355         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1356 }
1357
1358 #[test]
1359 fn test_fee_spike_violation_fails_htlc() {
1360         let chanmon_cfgs = create_chanmon_cfgs(2);
1361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1365
1366         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1367         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1368         let secp_ctx = Secp256k1::new();
1369         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1370
1371         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1372
1373         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1374         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1375         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1376         let msg = msgs::UpdateAddHTLC {
1377                 channel_id: chan.2,
1378                 htlc_id: 0,
1379                 amount_msat: htlc_msat,
1380                 payment_hash: payment_hash,
1381                 cltv_expiry: htlc_cltv,
1382                 onion_routing_packet: onion_packet,
1383         };
1384
1385         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1386
1387         // Now manually create the commitment_signed message corresponding to the update_add
1388         // nodes[0] just sent. In the code for construction of this message, "local" refers
1389         // to the sender of the message, and "remote" refers to the receiver.
1390
1391         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1392
1393         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1394
1395         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1396         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1397         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1398                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1399                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1400                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1401                 let chan_signer = local_chan.get_signer();
1402                 // Make the signer believe we validated another commitment, so we can release the secret
1403                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1404
1405                 let pubkeys = chan_signer.pubkeys();
1406                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1407                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1408                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1409                  chan_signer.pubkeys().funding_pubkey)
1410         };
1411         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1412                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1413                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1414                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1415                 let chan_signer = remote_chan.get_signer();
1416                 let pubkeys = chan_signer.pubkeys();
1417                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1418                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1419                  chan_signer.pubkeys().funding_pubkey)
1420         };
1421
1422         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1423         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1424                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1425
1426         // Build the remote commitment transaction so we can sign it, and then later use the
1427         // signature for the commitment_signed message.
1428         let local_chan_balance = 1313;
1429
1430         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1431                 offered: false,
1432                 amount_msat: 3460001,
1433                 cltv_expiry: htlc_cltv,
1434                 payment_hash,
1435                 transaction_output_index: Some(1),
1436         };
1437
1438         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1439
1440         let res = {
1441                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1442                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1443                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1444                 let local_chan_signer = local_chan.get_signer();
1445                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1446                         commitment_number,
1447                         95000,
1448                         local_chan_balance,
1449                         local_chan.opt_anchors(), local_funding, remote_funding,
1450                         commit_tx_keys.clone(),
1451                         feerate_per_kw,
1452                         &mut vec![(accepted_htlc_info, ())],
1453                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1454                 );
1455                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1456         };
1457
1458         let commit_signed_msg = msgs::CommitmentSigned {
1459                 channel_id: chan.2,
1460                 signature: res.0,
1461                 htlc_signatures: res.1
1462         };
1463
1464         // Send the commitment_signed message to the nodes[1].
1465         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1466         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1467
1468         // Send the RAA to nodes[1].
1469         let raa_msg = msgs::RevokeAndACK {
1470                 channel_id: chan.2,
1471                 per_commitment_secret: local_secret,
1472                 next_per_commitment_point: next_local_point
1473         };
1474         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1475
1476         let events = nodes[1].node.get_and_clear_pending_msg_events();
1477         assert_eq!(events.len(), 1);
1478         // Make sure the HTLC failed in the way we expect.
1479         match events[0] {
1480                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1481                         assert_eq!(update_fail_htlcs.len(), 1);
1482                         update_fail_htlcs[0].clone()
1483                 },
1484                 _ => panic!("Unexpected event"),
1485         };
1486         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1487                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1488
1489         check_added_monitors!(nodes[1], 2);
1490 }
1491
1492 #[test]
1493 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1494         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1495         // Set the fee rate for the channel very high, to the point where the fundee
1496         // sending any above-dust amount would result in a channel reserve violation.
1497         // In this test we check that we would be prevented from sending an HTLC in
1498         // this situation.
1499         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1502         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1503         let default_config = UserConfig::default();
1504         let opt_anchors = false;
1505
1506         let mut push_amt = 100_000_000;
1507         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1508
1509         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1510
1511         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1512
1513         // Sending exactly enough to hit the reserve amount should be accepted
1514         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1515                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1516         }
1517
1518         // However one more HTLC should be significantly over the reserve amount and fail.
1519         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1520         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1521                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1522         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1523         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1524 }
1525
1526 #[test]
1527 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1528         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1529         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1532         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1533         let default_config = UserConfig::default();
1534         let opt_anchors = false;
1535
1536         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1537         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1538         // transaction fee with 0 HTLCs (183 sats)).
1539         let mut push_amt = 100_000_000;
1540         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1541         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1542         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1543
1544         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1545         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1546                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1547         }
1548
1549         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1550         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1551         let secp_ctx = Secp256k1::new();
1552         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1553         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1554         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1555         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1556         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1557         let msg = msgs::UpdateAddHTLC {
1558                 channel_id: chan.2,
1559                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1560                 amount_msat: htlc_msat,
1561                 payment_hash: payment_hash,
1562                 cltv_expiry: htlc_cltv,
1563                 onion_routing_packet: onion_packet,
1564         };
1565
1566         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1567         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1568         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1569         assert_eq!(nodes[0].node.list_channels().len(), 0);
1570         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1571         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1572         check_added_monitors!(nodes[0], 1);
1573         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1574 }
1575
1576 #[test]
1577 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1578         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1579         // calculating our commitment transaction fee (this was previously broken).
1580         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1581         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1582
1583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1585         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1586         let default_config = UserConfig::default();
1587         let opt_anchors = false;
1588
1589         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1590         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1591         // transaction fee with 0 HTLCs (183 sats)).
1592         let mut push_amt = 100_000_000;
1593         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1594         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1595         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1596
1597         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1598                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1599         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1600         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1601         // commitment transaction fee.
1602         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1603
1604         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1605         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1606                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1607         }
1608
1609         // One more than the dust amt should fail, however.
1610         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1611         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1612                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1613 }
1614
1615 #[test]
1616 fn test_chan_init_feerate_unaffordability() {
1617         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1618         // channel reserve and feerate requirements.
1619         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1620         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1623         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1624         let default_config = UserConfig::default();
1625         let opt_anchors = false;
1626
1627         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1628         // HTLC.
1629         let mut push_amt = 100_000_000;
1630         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1631         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1632                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1633
1634         // During open, we don't have a "counterparty channel reserve" to check against, so that
1635         // requirement only comes into play on the open_channel handling side.
1636         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1637         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1638         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1639         open_channel_msg.push_msat += 1;
1640         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1641
1642         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1643         assert_eq!(msg_events.len(), 1);
1644         match msg_events[0] {
1645                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1646                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1647                 },
1648                 _ => panic!("Unexpected event"),
1649         }
1650 }
1651
1652 #[test]
1653 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1654         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1655         // calculating our counterparty's commitment transaction fee (this was previously broken).
1656         let chanmon_cfgs = create_chanmon_cfgs(2);
1657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1659         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1660         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1661
1662         let payment_amt = 46000; // Dust amount
1663         // In the previous code, these first four payments would succeed.
1664         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668
1669         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1674         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1675
1676         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1677         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1678         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1679         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 }
1681
1682 #[test]
1683 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1684         let chanmon_cfgs = create_chanmon_cfgs(3);
1685         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1686         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1687         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1688         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1689         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1690
1691         let feemsat = 239;
1692         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1693         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1694         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1695         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1696
1697         // Add a 2* and +1 for the fee spike reserve.
1698         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1699         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1700         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1701
1702         // Add a pending HTLC.
1703         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1704         let payment_event_1 = {
1705                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1706                 check_added_monitors!(nodes[0], 1);
1707
1708                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1709                 assert_eq!(events.len(), 1);
1710                 SendEvent::from_event(events.remove(0))
1711         };
1712         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1713
1714         // Attempt to trigger a channel reserve violation --> payment failure.
1715         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1716         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1717         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1718         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1719
1720         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1721         let secp_ctx = Secp256k1::new();
1722         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1723         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1724         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1725         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1726         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1727         let msg = msgs::UpdateAddHTLC {
1728                 channel_id: chan.2,
1729                 htlc_id: 1,
1730                 amount_msat: htlc_msat + 1,
1731                 payment_hash: our_payment_hash_1,
1732                 cltv_expiry: htlc_cltv,
1733                 onion_routing_packet: onion_packet,
1734         };
1735
1736         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1737         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1738         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1739         assert_eq!(nodes[1].node.list_channels().len(), 1);
1740         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1741         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1742         check_added_monitors!(nodes[1], 1);
1743         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1744 }
1745
1746 #[test]
1747 fn test_inbound_outbound_capacity_is_not_zero() {
1748         let chanmon_cfgs = create_chanmon_cfgs(2);
1749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1751         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1752         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1753         let channels0 = node_chanmgrs[0].list_channels();
1754         let channels1 = node_chanmgrs[1].list_channels();
1755         let default_config = UserConfig::default();
1756         assert_eq!(channels0.len(), 1);
1757         assert_eq!(channels1.len(), 1);
1758
1759         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1760         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1761         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1762
1763         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1764         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1765 }
1766
1767 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1768         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1769 }
1770
1771 #[test]
1772 fn test_channel_reserve_holding_cell_htlcs() {
1773         let chanmon_cfgs = create_chanmon_cfgs(3);
1774         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1775         // When this test was written, the default base fee floated based on the HTLC count.
1776         // It is now fixed, so we simply set the fee to the expected value here.
1777         let mut config = test_default_channel_config();
1778         config.channel_config.forwarding_fee_base_msat = 239;
1779         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1780         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1781         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1782         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1783
1784         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1785         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1786
1787         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1788         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1789
1790         macro_rules! expect_forward {
1791                 ($node: expr) => {{
1792                         let mut events = $node.node.get_and_clear_pending_msg_events();
1793                         assert_eq!(events.len(), 1);
1794                         check_added_monitors!($node, 1);
1795                         let payment_event = SendEvent::from_event(events.remove(0));
1796                         payment_event
1797                 }}
1798         }
1799
1800         let feemsat = 239; // set above
1801         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1802         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1803         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1804
1805         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1806
1807         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1808         {
1809                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1810                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1811                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1812                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1813                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1814
1815                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1816                         assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1817                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1818                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
1819         }
1820
1821         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1822         // nodes[0]'s wealth
1823         loop {
1824                 let amt_msat = recv_value_0 + total_fee_msat;
1825                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1826                 // Also, ensure that each payment has enough to be over the dust limit to
1827                 // ensure it'll be included in each commit tx fee calculation.
1828                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1829                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1830                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1831                         break;
1832                 }
1833
1834                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1835                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1836                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1837                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1838                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1839
1840                 let (stat01_, stat11_, stat12_, stat22_) = (
1841                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1842                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1843                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1844                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1845                 );
1846
1847                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1848                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1849                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1850                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1851                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1852         }
1853
1854         // adding pending output.
1855         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1856         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1857         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1858         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1859         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1860         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1861         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1862         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1863         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1864         // policy.
1865         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1866         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1867         let amt_msat_1 = recv_value_1 + total_fee_msat;
1868
1869         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1870         let payment_event_1 = {
1871                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1872                 check_added_monitors!(nodes[0], 1);
1873
1874                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1875                 assert_eq!(events.len(), 1);
1876                 SendEvent::from_event(events.remove(0))
1877         };
1878         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1879
1880         // channel reserve test with htlc pending output > 0
1881         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1882         {
1883                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1884                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1885                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1886                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1887         }
1888
1889         // split the rest to test holding cell
1890         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1891         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1892         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1893         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1894         {
1895                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1896                 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 + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1897         }
1898
1899         // now see if they go through on both sides
1900         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1901         // but this will stuck in the holding cell
1902         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1903         check_added_monitors!(nodes[0], 0);
1904         let events = nodes[0].node.get_and_clear_pending_events();
1905         assert_eq!(events.len(), 0);
1906
1907         // test with outbound holding cell amount > 0
1908         {
1909                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1910                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1911                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1912                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1913                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1914         }
1915
1916         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1917         // this will also stuck in the holding cell
1918         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1919         check_added_monitors!(nodes[0], 0);
1920         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1921         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1922
1923         // flush the pending htlc
1924         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1925         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1926         check_added_monitors!(nodes[1], 1);
1927
1928         // the pending htlc should be promoted to committed
1929         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1930         check_added_monitors!(nodes[0], 1);
1931         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1932
1933         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1934         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1935         // No commitment_signed so get_event_msg's assert(len == 1) passes
1936         check_added_monitors!(nodes[0], 1);
1937
1938         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1939         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1940         check_added_monitors!(nodes[1], 1);
1941
1942         expect_pending_htlcs_forwardable!(nodes[1]);
1943
1944         let ref payment_event_11 = expect_forward!(nodes[1]);
1945         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1946         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1947
1948         expect_pending_htlcs_forwardable!(nodes[2]);
1949         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1950
1951         // flush the htlcs in the holding cell
1952         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1953         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1954         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1955         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1956         expect_pending_htlcs_forwardable!(nodes[1]);
1957
1958         let ref payment_event_3 = expect_forward!(nodes[1]);
1959         assert_eq!(payment_event_3.msgs.len(), 2);
1960         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1961         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1962
1963         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1964         expect_pending_htlcs_forwardable!(nodes[2]);
1965
1966         let events = nodes[2].node.get_and_clear_pending_events();
1967         assert_eq!(events.len(), 2);
1968         match events[0] {
1969                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1970                         assert_eq!(our_payment_hash_21, *payment_hash);
1971                         assert_eq!(recv_value_21, amount_msat);
1972                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1973                         assert_eq!(via_channel_id, Some(chan_2.2));
1974                         match &purpose {
1975                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1976                                         assert!(payment_preimage.is_none());
1977                                         assert_eq!(our_payment_secret_21, *payment_secret);
1978                                 },
1979                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1980                         }
1981                 },
1982                 _ => panic!("Unexpected event"),
1983         }
1984         match events[1] {
1985                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1986                         assert_eq!(our_payment_hash_22, *payment_hash);
1987                         assert_eq!(recv_value_22, amount_msat);
1988                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1989                         assert_eq!(via_channel_id, Some(chan_2.2));
1990                         match &purpose {
1991                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1992                                         assert!(payment_preimage.is_none());
1993                                         assert_eq!(our_payment_secret_22, *payment_secret);
1994                                 },
1995                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1996                         }
1997                 },
1998                 _ => panic!("Unexpected event"),
1999         }
2000
2001         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2002         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2003         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2004
2005         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2006         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2007         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2008
2009         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2010         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) - (recv_value_3 + total_fee_msat);
2011         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2012         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2013         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2014
2015         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2016         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2017 }
2018
2019 #[test]
2020 fn channel_reserve_in_flight_removes() {
2021         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2022         // can send to its counterparty, but due to update ordering, the other side may not yet have
2023         // considered those HTLCs fully removed.
2024         // This tests that we don't count HTLCs which will not be included in the next remote
2025         // commitment transaction towards the reserve value (as it implies no commitment transaction
2026         // will be generated which violates the remote reserve value).
2027         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2028         // To test this we:
2029         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2030         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2031         //    you only consider the value of the first HTLC, it may not),
2032         //  * start routing a third HTLC from A to B,
2033         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2034         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2035         //  * deliver the first fulfill from B
2036         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2037         //    claim,
2038         //  * deliver A's response CS and RAA.
2039         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2040         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2041         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2042         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2043         let chanmon_cfgs = create_chanmon_cfgs(2);
2044         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2045         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2046         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2047         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2048
2049         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2050         // Route the first two HTLCs.
2051         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2052         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2053         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2054
2055         // Start routing the third HTLC (this is just used to get everyone in the right state).
2056         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2057         let send_1 = {
2058                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2059                 check_added_monitors!(nodes[0], 1);
2060                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2061                 assert_eq!(events.len(), 1);
2062                 SendEvent::from_event(events.remove(0))
2063         };
2064
2065         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2066         // initial fulfill/CS.
2067         nodes[1].node.claim_funds(payment_preimage_1);
2068         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2069         check_added_monitors!(nodes[1], 1);
2070         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2071
2072         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2073         // remove the second HTLC when we send the HTLC back from B to A.
2074         nodes[1].node.claim_funds(payment_preimage_2);
2075         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2076         check_added_monitors!(nodes[1], 1);
2077         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2078
2079         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2080         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2081         check_added_monitors!(nodes[0], 1);
2082         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2083         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2084
2085         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2086         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2087         check_added_monitors!(nodes[1], 1);
2088         // B is already AwaitingRAA, so cant generate a CS here
2089         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2090
2091         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2092         check_added_monitors!(nodes[1], 1);
2093         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2094
2095         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2096         check_added_monitors!(nodes[0], 1);
2097         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2098
2099         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2100         check_added_monitors!(nodes[1], 1);
2101         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2102
2103         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2104         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2105         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2106         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2107         // on-chain as necessary).
2108         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2109         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2110         check_added_monitors!(nodes[0], 1);
2111         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2112         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2113
2114         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2115         check_added_monitors!(nodes[1], 1);
2116         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2117
2118         expect_pending_htlcs_forwardable!(nodes[1]);
2119         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2120
2121         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2122         // resolve the second HTLC from A's point of view.
2123         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2124         check_added_monitors!(nodes[0], 1);
2125         expect_payment_path_successful!(nodes[0]);
2126         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2127
2128         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2129         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2130         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2131         let send_2 = {
2132                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2133                 check_added_monitors!(nodes[1], 1);
2134                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2135                 assert_eq!(events.len(), 1);
2136                 SendEvent::from_event(events.remove(0))
2137         };
2138
2139         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2140         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2141         check_added_monitors!(nodes[0], 1);
2142         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2143
2144         // Now just resolve all the outstanding messages/HTLCs for completeness...
2145
2146         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2147         check_added_monitors!(nodes[1], 1);
2148         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2149
2150         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2151         check_added_monitors!(nodes[1], 1);
2152
2153         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2154         check_added_monitors!(nodes[0], 1);
2155         expect_payment_path_successful!(nodes[0]);
2156         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2157
2158         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2159         check_added_monitors!(nodes[1], 1);
2160         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2161
2162         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2163         check_added_monitors!(nodes[0], 1);
2164
2165         expect_pending_htlcs_forwardable!(nodes[0]);
2166         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2167
2168         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2169         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2170 }
2171
2172 #[test]
2173 fn channel_monitor_network_test() {
2174         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2175         // tests that ChannelMonitor is able to recover from various states.
2176         let chanmon_cfgs = create_chanmon_cfgs(5);
2177         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2178         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2179         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2180
2181         // Create some initial channels
2182         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2183         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2184         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2185         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2186
2187         // Make sure all nodes are at the same starting height
2188         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2189         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2190         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2191         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2192         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2193
2194         // Rebalance the network a bit by relaying one payment through all the channels...
2195         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2197         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2198         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2199
2200         // Simple case with no pending HTLCs:
2201         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2202         check_added_monitors!(nodes[1], 1);
2203         check_closed_broadcast!(nodes[1], true);
2204         {
2205                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2206                 assert_eq!(node_txn.len(), 1);
2207                 mine_transaction(&nodes[0], &node_txn[0]);
2208                 check_added_monitors!(nodes[0], 1);
2209                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2210         }
2211         check_closed_broadcast!(nodes[0], true);
2212         assert_eq!(nodes[0].node.list_channels().len(), 0);
2213         assert_eq!(nodes[1].node.list_channels().len(), 1);
2214         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2215         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2216
2217         // One pending HTLC is discarded by the force-close:
2218         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2219
2220         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2221         // broadcasted until we reach the timelock time).
2222         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2223         check_closed_broadcast!(nodes[1], true);
2224         check_added_monitors!(nodes[1], 1);
2225         {
2226                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2227                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2228                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2229                 mine_transaction(&nodes[2], &node_txn[0]);
2230                 check_added_monitors!(nodes[2], 1);
2231                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2232         }
2233         check_closed_broadcast!(nodes[2], true);
2234         assert_eq!(nodes[1].node.list_channels().len(), 0);
2235         assert_eq!(nodes[2].node.list_channels().len(), 1);
2236         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2237         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2238
2239         macro_rules! claim_funds {
2240                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2241                         {
2242                                 $node.node.claim_funds($preimage);
2243                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2244                                 check_added_monitors!($node, 1);
2245
2246                                 let events = $node.node.get_and_clear_pending_msg_events();
2247                                 assert_eq!(events.len(), 1);
2248                                 match events[0] {
2249                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2250                                                 assert!(update_add_htlcs.is_empty());
2251                                                 assert!(update_fail_htlcs.is_empty());
2252                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2253                                         },
2254                                         _ => panic!("Unexpected event"),
2255                                 };
2256                         }
2257                 }
2258         }
2259
2260         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2261         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2262         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2263         check_added_monitors!(nodes[2], 1);
2264         check_closed_broadcast!(nodes[2], true);
2265         let node2_commitment_txid;
2266         {
2267                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2268                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2269                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2270                 node2_commitment_txid = node_txn[0].txid();
2271
2272                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2273                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2274                 mine_transaction(&nodes[3], &node_txn[0]);
2275                 check_added_monitors!(nodes[3], 1);
2276                 check_preimage_claim(&nodes[3], &node_txn);
2277         }
2278         check_closed_broadcast!(nodes[3], true);
2279         assert_eq!(nodes[2].node.list_channels().len(), 0);
2280         assert_eq!(nodes[3].node.list_channels().len(), 1);
2281         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2282         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2283
2284         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2285         // confusing us in the following tests.
2286         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2287
2288         // One pending HTLC to time out:
2289         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2290         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2291         // buffer space).
2292
2293         let (close_chan_update_1, close_chan_update_2) = {
2294                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2295                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2296                 assert_eq!(events.len(), 2);
2297                 let close_chan_update_1 = match events[0] {
2298                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2299                                 msg.clone()
2300                         },
2301                         _ => panic!("Unexpected event"),
2302                 };
2303                 match events[1] {
2304                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2305                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2306                         },
2307                         _ => panic!("Unexpected event"),
2308                 }
2309                 check_added_monitors!(nodes[3], 1);
2310
2311                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2312                 {
2313                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2314                         node_txn.retain(|tx| {
2315                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2316                                         false
2317                                 } else { true }
2318                         });
2319                 }
2320
2321                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2322
2323                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2324                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2325
2326                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2327                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2328                 assert_eq!(events.len(), 2);
2329                 let close_chan_update_2 = match events[0] {
2330                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2331                                 msg.clone()
2332                         },
2333                         _ => panic!("Unexpected event"),
2334                 };
2335                 match events[1] {
2336                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2337                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2338                         },
2339                         _ => panic!("Unexpected event"),
2340                 }
2341                 check_added_monitors!(nodes[4], 1);
2342                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2343
2344                 mine_transaction(&nodes[4], &node_txn[0]);
2345                 check_preimage_claim(&nodes[4], &node_txn);
2346                 (close_chan_update_1, close_chan_update_2)
2347         };
2348         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2349         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2350         assert_eq!(nodes[3].node.list_channels().len(), 0);
2351         assert_eq!(nodes[4].node.list_channels().len(), 0);
2352
2353         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2354                 ChannelMonitorUpdateStatus::Completed);
2355         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2356         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2357 }
2358
2359 #[test]
2360 fn test_justice_tx() {
2361         // Test justice txn built on revoked HTLC-Success tx, against both sides
2362         let mut alice_config = UserConfig::default();
2363         alice_config.channel_handshake_config.announced_channel = true;
2364         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2365         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2366         let mut bob_config = UserConfig::default();
2367         bob_config.channel_handshake_config.announced_channel = true;
2368         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2369         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2370         let user_cfgs = [Some(alice_config), Some(bob_config)];
2371         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2372         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2373         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2376         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2377         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2378         // Create some new channels:
2379         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2380
2381         // A pending HTLC which will be revoked:
2382         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2383         // Get the will-be-revoked local txn from nodes[0]
2384         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2385         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2386         assert_eq!(revoked_local_txn[0].input.len(), 1);
2387         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2388         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2389         assert_eq!(revoked_local_txn[1].input.len(), 1);
2390         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2391         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2392         // Revoke the old state
2393         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2394
2395         {
2396                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2397                 {
2398                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2399                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2400                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2401
2402                         check_spends!(node_txn[0], revoked_local_txn[0]);
2403                         node_txn.swap_remove(0);
2404                 }
2405                 check_added_monitors!(nodes[1], 1);
2406                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2407                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2408
2409                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2410                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2411                 // Verify broadcast of revoked HTLC-timeout
2412                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2413                 check_added_monitors!(nodes[0], 1);
2414                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2415                 // Broadcast revoked HTLC-timeout on node 1
2416                 mine_transaction(&nodes[1], &node_txn[1]);
2417                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2418         }
2419         get_announce_close_broadcast_events(&nodes, 0, 1);
2420
2421         assert_eq!(nodes[0].node.list_channels().len(), 0);
2422         assert_eq!(nodes[1].node.list_channels().len(), 0);
2423
2424         // We test justice_tx build by A on B's revoked HTLC-Success tx
2425         // Create some new channels:
2426         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2427         {
2428                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429                 node_txn.clear();
2430         }
2431
2432         // A pending HTLC which will be revoked:
2433         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2434         // Get the will-be-revoked local txn from B
2435         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2436         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2437         assert_eq!(revoked_local_txn[0].input.len(), 1);
2438         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2439         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2440         // Revoke the old state
2441         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2442         {
2443                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2444                 {
2445                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2446                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2447                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2448
2449                         check_spends!(node_txn[0], revoked_local_txn[0]);
2450                         node_txn.swap_remove(0);
2451                 }
2452                 check_added_monitors!(nodes[0], 1);
2453                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2454
2455                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2456                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2457                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2458                 check_added_monitors!(nodes[1], 1);
2459                 mine_transaction(&nodes[0], &node_txn[1]);
2460                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2461                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2462         }
2463         get_announce_close_broadcast_events(&nodes, 0, 1);
2464         assert_eq!(nodes[0].node.list_channels().len(), 0);
2465         assert_eq!(nodes[1].node.list_channels().len(), 0);
2466 }
2467
2468 #[test]
2469 fn revoked_output_claim() {
2470         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2471         // transaction is broadcast by its counterparty
2472         let chanmon_cfgs = create_chanmon_cfgs(2);
2473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2476         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2477         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2478         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2479         assert_eq!(revoked_local_txn.len(), 1);
2480         // Only output is the full channel value back to nodes[0]:
2481         assert_eq!(revoked_local_txn[0].output.len(), 1);
2482         // Send a payment through, updating everyone's latest commitment txn
2483         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2484
2485         // Inform nodes[1] that nodes[0] broadcast a stale tx
2486         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2487         check_added_monitors!(nodes[1], 1);
2488         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2489         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2490         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2491
2492         check_spends!(node_txn[0], revoked_local_txn[0]);
2493
2494         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2495         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2496         get_announce_close_broadcast_events(&nodes, 0, 1);
2497         check_added_monitors!(nodes[0], 1);
2498         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2499 }
2500
2501 #[test]
2502 fn claim_htlc_outputs_shared_tx() {
2503         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2504         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2505         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2509
2510         // Create some new channel:
2511         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2512
2513         // Rebalance the network to generate htlc in the two directions
2514         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2515         // 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
2516         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2517         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2518
2519         // Get the will-be-revoked local txn from node[0]
2520         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2521         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2522         assert_eq!(revoked_local_txn[0].input.len(), 1);
2523         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2524         assert_eq!(revoked_local_txn[1].input.len(), 1);
2525         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2526         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2527         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2528
2529         //Revoke the old state
2530         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2531
2532         {
2533                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2534                 check_added_monitors!(nodes[0], 1);
2535                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2536                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2537                 check_added_monitors!(nodes[1], 1);
2538                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2539                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2540                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2541
2542                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2543                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2544
2545                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2546                 check_spends!(node_txn[0], revoked_local_txn[0]);
2547
2548                 let mut witness_lens = BTreeSet::new();
2549                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2550                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2551                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2552                 assert_eq!(witness_lens.len(), 3);
2553                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2554                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2555                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2556
2557                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2558                 // ANTI_REORG_DELAY confirmations.
2559                 mine_transaction(&nodes[1], &node_txn[0]);
2560                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2561                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2562         }
2563         get_announce_close_broadcast_events(&nodes, 0, 1);
2564         assert_eq!(nodes[0].node.list_channels().len(), 0);
2565         assert_eq!(nodes[1].node.list_channels().len(), 0);
2566 }
2567
2568 #[test]
2569 fn claim_htlc_outputs_single_tx() {
2570         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2571         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2572         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2575         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2576
2577         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2578
2579         // Rebalance the network to generate htlc in the two directions
2580         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2581         // 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
2582         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2583         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2584         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2585
2586         // Get the will-be-revoked local txn from node[0]
2587         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2588
2589         //Revoke the old state
2590         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2591
2592         {
2593                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2594                 check_added_monitors!(nodes[0], 1);
2595                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2596                 check_added_monitors!(nodes[1], 1);
2597                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2598                 let mut events = nodes[0].node.get_and_clear_pending_events();
2599                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2600                 match events.last().unwrap() {
2601                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2602                         _ => panic!("Unexpected event"),
2603                 }
2604
2605                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2606                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2607
2608                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2609                 assert_eq!(node_txn.len(), 7);
2610
2611                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2612                 assert_eq!(node_txn[0].input.len(), 1);
2613                 check_spends!(node_txn[0], chan_1.3);
2614                 assert_eq!(node_txn[1].input.len(), 1);
2615                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2616                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2617                 check_spends!(node_txn[1], node_txn[0]);
2618
2619                 // Justice transactions are indices 2-3-4
2620                 assert_eq!(node_txn[2].input.len(), 1);
2621                 assert_eq!(node_txn[3].input.len(), 1);
2622                 assert_eq!(node_txn[4].input.len(), 1);
2623
2624                 check_spends!(node_txn[2], revoked_local_txn[0]);
2625                 check_spends!(node_txn[3], revoked_local_txn[0]);
2626                 check_spends!(node_txn[4], revoked_local_txn[0]);
2627
2628                 let mut witness_lens = BTreeSet::new();
2629                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2630                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2631                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2632                 assert_eq!(witness_lens.len(), 3);
2633                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2634                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2635                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2636
2637                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2638                 // ANTI_REORG_DELAY confirmations.
2639                 mine_transaction(&nodes[1], &node_txn[2]);
2640                 mine_transaction(&nodes[1], &node_txn[3]);
2641                 mine_transaction(&nodes[1], &node_txn[4]);
2642                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2643                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2644         }
2645         get_announce_close_broadcast_events(&nodes, 0, 1);
2646         assert_eq!(nodes[0].node.list_channels().len(), 0);
2647         assert_eq!(nodes[1].node.list_channels().len(), 0);
2648 }
2649
2650 #[test]
2651 fn test_htlc_on_chain_success() {
2652         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2653         // the preimage backward accordingly. So here we test that ChannelManager is
2654         // broadcasting the right event to other nodes in payment path.
2655         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2656         // A --------------------> B ----------------------> C (preimage)
2657         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2658         // commitment transaction was broadcast.
2659         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2660         // towards B.
2661         // B should be able to claim via preimage if A then broadcasts its local tx.
2662         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2663         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2664         // PaymentSent event).
2665
2666         let chanmon_cfgs = create_chanmon_cfgs(3);
2667         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2668         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2669         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2670
2671         // Create some initial channels
2672         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2673         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2674
2675         // Ensure all nodes are at the same height
2676         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2677         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2678         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2679         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2680
2681         // Rebalance the network a bit by relaying one payment through all the channels...
2682         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2683         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2684
2685         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2686         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2687
2688         // Broadcast legit commitment tx from C on B's chain
2689         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2690         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2691         assert_eq!(commitment_tx.len(), 1);
2692         check_spends!(commitment_tx[0], chan_2.3);
2693         nodes[2].node.claim_funds(our_payment_preimage);
2694         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2695         nodes[2].node.claim_funds(our_payment_preimage_2);
2696         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2697         check_added_monitors!(nodes[2], 2);
2698         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2699         assert!(updates.update_add_htlcs.is_empty());
2700         assert!(updates.update_fail_htlcs.is_empty());
2701         assert!(updates.update_fail_malformed_htlcs.is_empty());
2702         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2703
2704         mine_transaction(&nodes[2], &commitment_tx[0]);
2705         check_closed_broadcast!(nodes[2], true);
2706         check_added_monitors!(nodes[2], 1);
2707         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2708         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2709         assert_eq!(node_txn.len(), 2);
2710         check_spends!(node_txn[0], commitment_tx[0]);
2711         check_spends!(node_txn[1], commitment_tx[0]);
2712         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2713         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2714         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2715         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2716         assert_eq!(node_txn[0].lock_time.0, 0);
2717         assert_eq!(node_txn[1].lock_time.0, 0);
2718
2719         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2720         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2721         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2722         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2723         {
2724                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2725                 assert_eq!(added_monitors.len(), 1);
2726                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2727                 added_monitors.clear();
2728         }
2729         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2730         assert_eq!(forwarded_events.len(), 3);
2731         match forwarded_events[0] {
2732                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2733                 _ => panic!("Unexpected event"),
2734         }
2735         let chan_id = Some(chan_1.2);
2736         match forwarded_events[1] {
2737                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2738                         assert_eq!(fee_earned_msat, Some(1000));
2739                         assert_eq!(prev_channel_id, chan_id);
2740                         assert_eq!(claim_from_onchain_tx, true);
2741                         assert_eq!(next_channel_id, Some(chan_2.2));
2742                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2743                 },
2744                 _ => panic!()
2745         }
2746         match forwarded_events[2] {
2747                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2748                         assert_eq!(fee_earned_msat, Some(1000));
2749                         assert_eq!(prev_channel_id, chan_id);
2750                         assert_eq!(claim_from_onchain_tx, true);
2751                         assert_eq!(next_channel_id, Some(chan_2.2));
2752                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2753                 },
2754                 _ => panic!()
2755         }
2756         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2757         {
2758                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2759                 assert_eq!(added_monitors.len(), 2);
2760                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2761                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2762                 added_monitors.clear();
2763         }
2764         assert_eq!(events.len(), 3);
2765
2766         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2767         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2768
2769         match nodes_2_event {
2770                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2771                 _ => panic!("Unexpected event"),
2772         }
2773
2774         match nodes_0_event {
2775                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2776                         assert!(update_add_htlcs.is_empty());
2777                         assert!(update_fail_htlcs.is_empty());
2778                         assert_eq!(update_fulfill_htlcs.len(), 1);
2779                         assert!(update_fail_malformed_htlcs.is_empty());
2780                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2781                 },
2782                 _ => panic!("Unexpected event"),
2783         };
2784
2785         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2786         match events[0] {
2787                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2788                 _ => panic!("Unexpected event"),
2789         }
2790
2791         macro_rules! check_tx_local_broadcast {
2792                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2793                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2794                         assert_eq!(node_txn.len(), 2);
2795                         // Node[1]: 2 * HTLC-timeout tx
2796                         // Node[0]: 2 * HTLC-timeout tx
2797                         check_spends!(node_txn[0], $commitment_tx);
2798                         check_spends!(node_txn[1], $commitment_tx);
2799                         assert_ne!(node_txn[0].lock_time.0, 0);
2800                         assert_ne!(node_txn[1].lock_time.0, 0);
2801                         if $htlc_offered {
2802                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2803                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2804                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2805                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2806                         } else {
2807                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2808                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2809                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2810                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2811                         }
2812                         node_txn.clear();
2813                 } }
2814         }
2815         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2816         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2817
2818         // Broadcast legit commitment tx from A on B's chain
2819         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2820         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2821         check_spends!(node_a_commitment_tx[0], chan_1.3);
2822         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2823         check_closed_broadcast!(nodes[1], true);
2824         check_added_monitors!(nodes[1], 1);
2825         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2826         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2827         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2828         let commitment_spend =
2829                 if node_txn.len() == 1 {
2830                         &node_txn[0]
2831                 } else {
2832                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2833                         // FullBlockViaListen
2834                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2835                                 check_spends!(node_txn[1], commitment_tx[0]);
2836                                 check_spends!(node_txn[2], commitment_tx[0]);
2837                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2838                                 &node_txn[0]
2839                         } else {
2840                                 check_spends!(node_txn[0], commitment_tx[0]);
2841                                 check_spends!(node_txn[1], commitment_tx[0]);
2842                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2843                                 &node_txn[2]
2844                         }
2845                 };
2846
2847         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2848         assert_eq!(commitment_spend.input.len(), 2);
2849         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2850         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2851         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2852         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2853         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2854         // we already checked the same situation with A.
2855
2856         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2857         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2858         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2859         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2860         check_closed_broadcast!(nodes[0], true);
2861         check_added_monitors!(nodes[0], 1);
2862         let events = nodes[0].node.get_and_clear_pending_events();
2863         assert_eq!(events.len(), 5);
2864         let mut first_claimed = false;
2865         for event in events {
2866                 match event {
2867                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2868                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2869                                         assert!(!first_claimed);
2870                                         first_claimed = true;
2871                                 } else {
2872                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2873                                         assert_eq!(payment_hash, payment_hash_2);
2874                                 }
2875                         },
2876                         Event::PaymentPathSuccessful { .. } => {},
2877                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2878                         _ => panic!("Unexpected event"),
2879                 }
2880         }
2881         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2882 }
2883
2884 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2885         // Test that in case of a unilateral close onchain, we detect the state of output and
2886         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2887         // broadcasting the right event to other nodes in payment path.
2888         // A ------------------> B ----------------------> C (timeout)
2889         //    B's commitment tx                 C's commitment tx
2890         //            \                                  \
2891         //         B's HTLC timeout tx               B's timeout tx
2892
2893         let chanmon_cfgs = create_chanmon_cfgs(3);
2894         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2895         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2896         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2897         *nodes[0].connect_style.borrow_mut() = connect_style;
2898         *nodes[1].connect_style.borrow_mut() = connect_style;
2899         *nodes[2].connect_style.borrow_mut() = connect_style;
2900
2901         // Create some intial channels
2902         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2903         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2904
2905         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2906         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2907         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2908
2909         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2910
2911         // Broadcast legit commitment tx from C on B's chain
2912         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2913         check_spends!(commitment_tx[0], chan_2.3);
2914         nodes[2].node.fail_htlc_backwards(&payment_hash);
2915         check_added_monitors!(nodes[2], 0);
2916         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2917         check_added_monitors!(nodes[2], 1);
2918
2919         let events = nodes[2].node.get_and_clear_pending_msg_events();
2920         assert_eq!(events.len(), 1);
2921         match events[0] {
2922                 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, .. } } => {
2923                         assert!(update_add_htlcs.is_empty());
2924                         assert!(!update_fail_htlcs.is_empty());
2925                         assert!(update_fulfill_htlcs.is_empty());
2926                         assert!(update_fail_malformed_htlcs.is_empty());
2927                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2928                 },
2929                 _ => panic!("Unexpected event"),
2930         };
2931         mine_transaction(&nodes[2], &commitment_tx[0]);
2932         check_closed_broadcast!(nodes[2], true);
2933         check_added_monitors!(nodes[2], 1);
2934         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2935         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2936         assert_eq!(node_txn.len(), 0);
2937
2938         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2939         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2940         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2941         mine_transaction(&nodes[1], &commitment_tx[0]);
2942         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2943         let timeout_tx;
2944         {
2945                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2946                 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2947
2948                 check_spends!(node_txn[2], commitment_tx[0]);
2949                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2950
2951                 check_spends!(node_txn[0], chan_2.3);
2952                 check_spends!(node_txn[1], node_txn[0]);
2953                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2954                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2955
2956                 timeout_tx = node_txn[2].clone();
2957                 node_txn.clear();
2958         }
2959
2960         mine_transaction(&nodes[1], &timeout_tx);
2961         check_added_monitors!(nodes[1], 1);
2962         check_closed_broadcast!(nodes[1], true);
2963
2964         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2965
2966         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
2967         check_added_monitors!(nodes[1], 1);
2968         let events = nodes[1].node.get_and_clear_pending_msg_events();
2969         assert_eq!(events.len(), 1);
2970         match events[0] {
2971                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2972                         assert!(update_add_htlcs.is_empty());
2973                         assert!(!update_fail_htlcs.is_empty());
2974                         assert!(update_fulfill_htlcs.is_empty());
2975                         assert!(update_fail_malformed_htlcs.is_empty());
2976                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2977                 },
2978                 _ => panic!("Unexpected event"),
2979         };
2980
2981         // Broadcast legit commitment tx from B on A's chain
2982         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2983         check_spends!(commitment_tx[0], chan_1.3);
2984
2985         mine_transaction(&nodes[0], &commitment_tx[0]);
2986         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2987
2988         check_closed_broadcast!(nodes[0], true);
2989         check_added_monitors!(nodes[0], 1);
2990         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2991         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2992         assert_eq!(node_txn.len(), 1);
2993         check_spends!(node_txn[0], commitment_tx[0]);
2994         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2995 }
2996
2997 #[test]
2998 fn test_htlc_on_chain_timeout() {
2999         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3000         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3001         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3002 }
3003
3004 #[test]
3005 fn test_simple_commitment_revoked_fail_backward() {
3006         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3007         // and fail backward accordingly.
3008
3009         let chanmon_cfgs = create_chanmon_cfgs(3);
3010         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3011         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3012         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3013
3014         // Create some initial channels
3015         create_announced_chan_between_nodes(&nodes, 0, 1);
3016         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3017
3018         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3019         // Get the will-be-revoked local txn from nodes[2]
3020         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3021         // Revoke the old state
3022         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3023
3024         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3025
3026         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3027         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3028         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3029         check_added_monitors!(nodes[1], 1);
3030         check_closed_broadcast!(nodes[1], true);
3031
3032         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3033         check_added_monitors!(nodes[1], 1);
3034         let events = nodes[1].node.get_and_clear_pending_msg_events();
3035         assert_eq!(events.len(), 1);
3036         match events[0] {
3037                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3038                         assert!(update_add_htlcs.is_empty());
3039                         assert_eq!(update_fail_htlcs.len(), 1);
3040                         assert!(update_fulfill_htlcs.is_empty());
3041                         assert!(update_fail_malformed_htlcs.is_empty());
3042                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3043
3044                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3045                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3046                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3047                 },
3048                 _ => panic!("Unexpected event"),
3049         }
3050 }
3051
3052 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3053         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3054         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3055         // commitment transaction anymore.
3056         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3057         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3058         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3059         // technically disallowed and we should probably handle it reasonably.
3060         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3061         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3062         // transactions:
3063         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3064         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3065         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3066         //   and once they revoke the previous commitment transaction (allowing us to send a new
3067         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3068         let chanmon_cfgs = create_chanmon_cfgs(3);
3069         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3070         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3071         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3072
3073         // Create some initial channels
3074         create_announced_chan_between_nodes(&nodes, 0, 1);
3075         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3076
3077         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3078         // Get the will-be-revoked local txn from nodes[2]
3079         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3080         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3081         // Revoke the old state
3082         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3083
3084         let value = if use_dust {
3085                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3086                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3087                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3088                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3089         } else { 3000000 };
3090
3091         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3092         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3093         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3094
3095         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3096         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3097         check_added_monitors!(nodes[2], 1);
3098         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3099         assert!(updates.update_add_htlcs.is_empty());
3100         assert!(updates.update_fulfill_htlcs.is_empty());
3101         assert!(updates.update_fail_malformed_htlcs.is_empty());
3102         assert_eq!(updates.update_fail_htlcs.len(), 1);
3103         assert!(updates.update_fee.is_none());
3104         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3105         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3106         // Drop the last RAA from 3 -> 2
3107
3108         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3109         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3110         check_added_monitors!(nodes[2], 1);
3111         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3112         assert!(updates.update_add_htlcs.is_empty());
3113         assert!(updates.update_fulfill_htlcs.is_empty());
3114         assert!(updates.update_fail_malformed_htlcs.is_empty());
3115         assert_eq!(updates.update_fail_htlcs.len(), 1);
3116         assert!(updates.update_fee.is_none());
3117         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3118         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3119         check_added_monitors!(nodes[1], 1);
3120         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3121         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3122         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3123         check_added_monitors!(nodes[2], 1);
3124
3125         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3126         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3127         check_added_monitors!(nodes[2], 1);
3128         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3129         assert!(updates.update_add_htlcs.is_empty());
3130         assert!(updates.update_fulfill_htlcs.is_empty());
3131         assert!(updates.update_fail_malformed_htlcs.is_empty());
3132         assert_eq!(updates.update_fail_htlcs.len(), 1);
3133         assert!(updates.update_fee.is_none());
3134         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3135         // At this point first_payment_hash has dropped out of the latest two commitment
3136         // transactions that nodes[1] is tracking...
3137         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3138         check_added_monitors!(nodes[1], 1);
3139         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3140         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3141         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3142         check_added_monitors!(nodes[2], 1);
3143
3144         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3145         // on nodes[2]'s RAA.
3146         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3147         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3149         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3150         check_added_monitors!(nodes[1], 0);
3151
3152         if deliver_bs_raa {
3153                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3154                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3155                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3156                 check_added_monitors!(nodes[1], 1);
3157                 let events = nodes[1].node.get_and_clear_pending_events();
3158                 assert_eq!(events.len(), 2);
3159                 match events[0] {
3160                         Event::PendingHTLCsForwardable { .. } => { },
3161                         _ => panic!("Unexpected event"),
3162                 };
3163                 match events[1] {
3164                         Event::HTLCHandlingFailed { .. } => { },
3165                         _ => panic!("Unexpected event"),
3166                 }
3167                 // Deliberately don't process the pending fail-back so they all fail back at once after
3168                 // block connection just like the !deliver_bs_raa case
3169         }
3170
3171         let mut failed_htlcs = HashSet::new();
3172         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3173
3174         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3175         check_added_monitors!(nodes[1], 1);
3176         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3177
3178         let events = nodes[1].node.get_and_clear_pending_events();
3179         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3180         match events[0] {
3181                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3182                 _ => panic!("Unexepected event"),
3183         }
3184         match events[1] {
3185                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3186                         assert_eq!(*payment_hash, fourth_payment_hash);
3187                 },
3188                 _ => panic!("Unexpected event"),
3189         }
3190         match events[2] {
3191                 Event::PaymentFailed { ref payment_hash, .. } => {
3192                         assert_eq!(*payment_hash, fourth_payment_hash);
3193                 },
3194                 _ => panic!("Unexpected event"),
3195         }
3196
3197         nodes[1].node.process_pending_htlc_forwards();
3198         check_added_monitors!(nodes[1], 1);
3199
3200         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3201         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3202
3203         if deliver_bs_raa {
3204                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3205                 match nodes_2_event {
3206                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3207                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3208                                 assert_eq!(update_add_htlcs.len(), 1);
3209                                 assert!(update_fulfill_htlcs.is_empty());
3210                                 assert!(update_fail_htlcs.is_empty());
3211                                 assert!(update_fail_malformed_htlcs.is_empty());
3212                         },
3213                         _ => panic!("Unexpected event"),
3214                 }
3215         }
3216
3217         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3218         match nodes_2_event {
3219                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3220                         assert_eq!(channel_id, chan_2.2);
3221                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3222                 },
3223                 _ => panic!("Unexpected event"),
3224         }
3225
3226         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3227         match nodes_0_event {
3228                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3229                         assert!(update_add_htlcs.is_empty());
3230                         assert_eq!(update_fail_htlcs.len(), 3);
3231                         assert!(update_fulfill_htlcs.is_empty());
3232                         assert!(update_fail_malformed_htlcs.is_empty());
3233                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3234
3235                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3236                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3237                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3238
3239                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3240
3241                         let events = nodes[0].node.get_and_clear_pending_events();
3242                         assert_eq!(events.len(), 6);
3243                         match events[0] {
3244                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3245                                         assert!(failed_htlcs.insert(payment_hash.0));
3246                                         // If we delivered B's RAA we got an unknown preimage error, not something
3247                                         // that we should update our routing table for.
3248                                         if !deliver_bs_raa {
3249                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3250                                         }
3251                                 },
3252                                 _ => panic!("Unexpected event"),
3253                         }
3254                         match events[1] {
3255                                 Event::PaymentFailed { ref payment_hash, .. } => {
3256                                         assert_eq!(*payment_hash, first_payment_hash);
3257                                 },
3258                                 _ => panic!("Unexpected event"),
3259                         }
3260                         match events[2] {
3261                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3262                                         assert!(failed_htlcs.insert(payment_hash.0));
3263                                 },
3264                                 _ => panic!("Unexpected event"),
3265                         }
3266                         match events[3] {
3267                                 Event::PaymentFailed { ref payment_hash, .. } => {
3268                                         assert_eq!(*payment_hash, second_payment_hash);
3269                                 },
3270                                 _ => panic!("Unexpected event"),
3271                         }
3272                         match events[4] {
3273                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3274                                         assert!(failed_htlcs.insert(payment_hash.0));
3275                                 },
3276                                 _ => panic!("Unexpected event"),
3277                         }
3278                         match events[5] {
3279                                 Event::PaymentFailed { ref payment_hash, .. } => {
3280                                         assert_eq!(*payment_hash, third_payment_hash);
3281                                 },
3282                                 _ => panic!("Unexpected event"),
3283                         }
3284                 },
3285                 _ => panic!("Unexpected event"),
3286         }
3287
3288         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3289         match events[0] {
3290                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3291                 _ => panic!("Unexpected event"),
3292         }
3293
3294         assert!(failed_htlcs.contains(&first_payment_hash.0));
3295         assert!(failed_htlcs.contains(&second_payment_hash.0));
3296         assert!(failed_htlcs.contains(&third_payment_hash.0));
3297 }
3298
3299 #[test]
3300 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3301         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3302         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3303         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3304         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3305 }
3306
3307 #[test]
3308 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3309         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3310         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3311         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3312         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3313 }
3314
3315 #[test]
3316 fn fail_backward_pending_htlc_upon_channel_failure() {
3317         let chanmon_cfgs = create_chanmon_cfgs(2);
3318         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3319         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3320         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3321         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3322
3323         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3324         {
3325                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3326                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3327                 check_added_monitors!(nodes[0], 1);
3328
3329                 let payment_event = {
3330                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3331                         assert_eq!(events.len(), 1);
3332                         SendEvent::from_event(events.remove(0))
3333                 };
3334                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3335                 assert_eq!(payment_event.msgs.len(), 1);
3336         }
3337
3338         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3339         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3340         {
3341                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3342                 check_added_monitors!(nodes[0], 0);
3343
3344                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3345         }
3346
3347         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3348         {
3349                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3350
3351                 let secp_ctx = Secp256k1::new();
3352                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3353                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3354                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3355                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3356                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3357
3358                 // Send a 0-msat update_add_htlc to fail the channel.
3359                 let update_add_htlc = msgs::UpdateAddHTLC {
3360                         channel_id: chan.2,
3361                         htlc_id: 0,
3362                         amount_msat: 0,
3363                         payment_hash,
3364                         cltv_expiry,
3365                         onion_routing_packet,
3366                 };
3367                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3368         }
3369         let events = nodes[0].node.get_and_clear_pending_events();
3370         assert_eq!(events.len(), 3);
3371         // Check that Alice fails backward the pending HTLC from the second payment.
3372         match events[0] {
3373                 Event::PaymentPathFailed { payment_hash, .. } => {
3374                         assert_eq!(payment_hash, failed_payment_hash);
3375                 },
3376                 _ => panic!("Unexpected event"),
3377         }
3378         match events[1] {
3379                 Event::PaymentFailed { payment_hash, .. } => {
3380                         assert_eq!(payment_hash, failed_payment_hash);
3381                 },
3382                 _ => panic!("Unexpected event"),
3383         }
3384         match events[2] {
3385                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3386                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3387                 },
3388                 _ => panic!("Unexpected event {:?}", events[1]),
3389         }
3390         check_closed_broadcast!(nodes[0], true);
3391         check_added_monitors!(nodes[0], 1);
3392 }
3393
3394 #[test]
3395 fn test_htlc_ignore_latest_remote_commitment() {
3396         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3397         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3398         let chanmon_cfgs = create_chanmon_cfgs(2);
3399         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3400         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3401         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3402         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3403                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3404                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3405                 // connect_style.
3406                 return;
3407         }
3408         create_announced_chan_between_nodes(&nodes, 0, 1);
3409
3410         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3411         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3412         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3413         check_closed_broadcast!(nodes[0], true);
3414         check_added_monitors!(nodes[0], 1);
3415         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3416
3417         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3418         assert_eq!(node_txn.len(), 3);
3419         assert_eq!(node_txn[0], node_txn[1]);
3420
3421         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3422         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3423         check_closed_broadcast!(nodes[1], true);
3424         check_added_monitors!(nodes[1], 1);
3425         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3426
3427         // Duplicate the connect_block call since this may happen due to other listeners
3428         // registering new transactions
3429         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3430 }
3431
3432 #[test]
3433 fn test_force_close_fail_back() {
3434         // Check which HTLCs are failed-backwards on channel force-closure
3435         let chanmon_cfgs = create_chanmon_cfgs(3);
3436         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3437         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3438         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3439         create_announced_chan_between_nodes(&nodes, 0, 1);
3440         create_announced_chan_between_nodes(&nodes, 1, 2);
3441
3442         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3443
3444         let mut payment_event = {
3445                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3446                 check_added_monitors!(nodes[0], 1);
3447
3448                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3449                 assert_eq!(events.len(), 1);
3450                 SendEvent::from_event(events.remove(0))
3451         };
3452
3453         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3454         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3455
3456         expect_pending_htlcs_forwardable!(nodes[1]);
3457
3458         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3459         assert_eq!(events_2.len(), 1);
3460         payment_event = SendEvent::from_event(events_2.remove(0));
3461         assert_eq!(payment_event.msgs.len(), 1);
3462
3463         check_added_monitors!(nodes[1], 1);
3464         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3465         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3466         check_added_monitors!(nodes[2], 1);
3467         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3468
3469         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3470         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3471         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3472
3473         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3474         check_closed_broadcast!(nodes[2], true);
3475         check_added_monitors!(nodes[2], 1);
3476         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3477         let tx = {
3478                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3479                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3480                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3481                 // back to nodes[1] upon timeout otherwise.
3482                 assert_eq!(node_txn.len(), 1);
3483                 node_txn.remove(0)
3484         };
3485
3486         mine_transaction(&nodes[1], &tx);
3487
3488         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3489         check_closed_broadcast!(nodes[1], true);
3490         check_added_monitors!(nodes[1], 1);
3491         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3492
3493         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3494         {
3495                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3496                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3497         }
3498         mine_transaction(&nodes[2], &tx);
3499         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3500         assert_eq!(node_txn.len(), 1);
3501         assert_eq!(node_txn[0].input.len(), 1);
3502         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3503         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3504         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3505
3506         check_spends!(node_txn[0], tx);
3507 }
3508
3509 #[test]
3510 fn test_dup_events_on_peer_disconnect() {
3511         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3512         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3513         // as we used to generate the event immediately upon receipt of the payment preimage in the
3514         // update_fulfill_htlc message.
3515
3516         let chanmon_cfgs = create_chanmon_cfgs(2);
3517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3520         create_announced_chan_between_nodes(&nodes, 0, 1);
3521
3522         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3523
3524         nodes[1].node.claim_funds(payment_preimage);
3525         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3526         check_added_monitors!(nodes[1], 1);
3527         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3528         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3529         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3530
3531         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3532         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3533
3534         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3535         expect_payment_path_successful!(nodes[0]);
3536 }
3537
3538 #[test]
3539 fn test_peer_disconnected_before_funding_broadcasted() {
3540         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3541         // before the funding transaction has been broadcasted.
3542         let chanmon_cfgs = create_chanmon_cfgs(2);
3543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3545         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3546
3547         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3548         // broadcasted, even though it's created by `nodes[0]`.
3549         let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3550         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3551         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3552         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3553         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3554
3555         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3556         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3557
3558         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3559
3560         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3561         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3562
3563         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3564         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3565         // broadcasted.
3566         {
3567                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3568         }
3569
3570         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3571         // disconnected before the funding transaction was broadcasted.
3572         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3573         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3574
3575         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3576         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3577 }
3578
3579 #[test]
3580 fn test_simple_peer_disconnect() {
3581         // Test that we can reconnect when there are no lost messages
3582         let chanmon_cfgs = create_chanmon_cfgs(3);
3583         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3584         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3585         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3586         create_announced_chan_between_nodes(&nodes, 0, 1);
3587         create_announced_chan_between_nodes(&nodes, 1, 2);
3588
3589         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3590         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3591         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3592
3593         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3594         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3595         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3596         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3597
3598         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3599         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3600         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3601
3602         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3603         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3604         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3605         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3606
3607         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3608         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3609
3610         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3611         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3612
3613         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3614         {
3615                 let events = nodes[0].node.get_and_clear_pending_events();
3616                 assert_eq!(events.len(), 4);
3617                 match events[0] {
3618                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3619                                 assert_eq!(payment_preimage, payment_preimage_3);
3620                                 assert_eq!(payment_hash, payment_hash_3);
3621                         },
3622                         _ => panic!("Unexpected event"),
3623                 }
3624                 match events[1] {
3625                         Event::PaymentPathSuccessful { .. } => {},
3626                         _ => panic!("Unexpected event"),
3627                 }
3628                 match events[2] {
3629                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3630                                 assert_eq!(payment_hash, payment_hash_5);
3631                                 assert!(payment_failed_permanently);
3632                         },
3633                         _ => panic!("Unexpected event"),
3634                 }
3635                 match events[3] {
3636                         Event::PaymentFailed { payment_hash, .. } => {
3637                                 assert_eq!(payment_hash, payment_hash_5);
3638                         },
3639                         _ => panic!("Unexpected event"),
3640                 }
3641         }
3642
3643         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3644         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3645 }
3646
3647 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3648         // Test that we can reconnect when in-flight HTLC updates get dropped
3649         let chanmon_cfgs = create_chanmon_cfgs(2);
3650         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3651         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3652         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3653
3654         let mut as_channel_ready = None;
3655         let channel_id = if messages_delivered == 0 {
3656                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3657                 as_channel_ready = Some(channel_ready);
3658                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3659                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3660                 // it before the channel_reestablish message.
3661                 chan_id
3662         } else {
3663                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3664         };
3665
3666         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3667
3668         let payment_event = {
3669                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3670                 check_added_monitors!(nodes[0], 1);
3671
3672                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3673                 assert_eq!(events.len(), 1);
3674                 SendEvent::from_event(events.remove(0))
3675         };
3676         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3677
3678         if messages_delivered < 2 {
3679                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3680         } else {
3681                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3682                 if messages_delivered >= 3 {
3683                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3684                         check_added_monitors!(nodes[1], 1);
3685                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3686
3687                         if messages_delivered >= 4 {
3688                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3689                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3690                                 check_added_monitors!(nodes[0], 1);
3691
3692                                 if messages_delivered >= 5 {
3693                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3694                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3695                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3696                                         check_added_monitors!(nodes[0], 1);
3697
3698                                         if messages_delivered >= 6 {
3699                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3700                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3701                                                 check_added_monitors!(nodes[1], 1);
3702                                         }
3703                                 }
3704                         }
3705                 }
3706         }
3707
3708         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3709         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3710         if messages_delivered < 3 {
3711                 if simulate_broken_lnd {
3712                         // lnd has a long-standing bug where they send a channel_ready prior to a
3713                         // channel_reestablish if you reconnect prior to channel_ready time.
3714                         //
3715                         // Here we simulate that behavior, delivering a channel_ready immediately on
3716                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3717                         // in `reconnect_nodes` but we currently don't fail based on that.
3718                         //
3719                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3720                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3721                 }
3722                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3723                 // received on either side, both sides will need to resend them.
3724                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3725         } else if messages_delivered == 3 {
3726                 // nodes[0] still wants its RAA + commitment_signed
3727                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3728         } else if messages_delivered == 4 {
3729                 // nodes[0] still wants its commitment_signed
3730                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3731         } else if messages_delivered == 5 {
3732                 // nodes[1] still wants its final RAA
3733                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3734         } else if messages_delivered == 6 {
3735                 // Everything was delivered...
3736                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3737         }
3738
3739         let events_1 = nodes[1].node.get_and_clear_pending_events();
3740         if messages_delivered == 0 {
3741                 assert_eq!(events_1.len(), 2);
3742                 match events_1[0] {
3743                         Event::ChannelReady { .. } => { },
3744                         _ => panic!("Unexpected event"),
3745                 };
3746                 match events_1[1] {
3747                         Event::PendingHTLCsForwardable { .. } => { },
3748                         _ => panic!("Unexpected event"),
3749                 };
3750         } else {
3751                 assert_eq!(events_1.len(), 1);
3752                 match events_1[0] {
3753                         Event::PendingHTLCsForwardable { .. } => { },
3754                         _ => panic!("Unexpected event"),
3755                 };
3756         }
3757
3758         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3759         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3760         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3761
3762         nodes[1].node.process_pending_htlc_forwards();
3763
3764         let events_2 = nodes[1].node.get_and_clear_pending_events();
3765         assert_eq!(events_2.len(), 1);
3766         match events_2[0] {
3767                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3768                         assert_eq!(payment_hash_1, *payment_hash);
3769                         assert_eq!(amount_msat, 1_000_000);
3770                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3771                         assert_eq!(via_channel_id, Some(channel_id));
3772                         match &purpose {
3773                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3774                                         assert!(payment_preimage.is_none());
3775                                         assert_eq!(payment_secret_1, *payment_secret);
3776                                 },
3777                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3778                         }
3779                 },
3780                 _ => panic!("Unexpected event"),
3781         }
3782
3783         nodes[1].node.claim_funds(payment_preimage_1);
3784         check_added_monitors!(nodes[1], 1);
3785         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3786
3787         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3788         assert_eq!(events_3.len(), 1);
3789         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3790                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3791                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3792                         assert!(updates.update_add_htlcs.is_empty());
3793                         assert!(updates.update_fail_htlcs.is_empty());
3794                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3795                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3796                         assert!(updates.update_fee.is_none());
3797                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3798                 },
3799                 _ => panic!("Unexpected event"),
3800         };
3801
3802         if messages_delivered >= 1 {
3803                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3804
3805                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3806                 assert_eq!(events_4.len(), 1);
3807                 match events_4[0] {
3808                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3809                                 assert_eq!(payment_preimage_1, *payment_preimage);
3810                                 assert_eq!(payment_hash_1, *payment_hash);
3811                         },
3812                         _ => panic!("Unexpected event"),
3813                 }
3814
3815                 if messages_delivered >= 2 {
3816                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3817                         check_added_monitors!(nodes[0], 1);
3818                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3819
3820                         if messages_delivered >= 3 {
3821                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3822                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3823                                 check_added_monitors!(nodes[1], 1);
3824
3825                                 if messages_delivered >= 4 {
3826                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3827                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3828                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3829                                         check_added_monitors!(nodes[1], 1);
3830
3831                                         if messages_delivered >= 5 {
3832                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3833                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3834                                                 check_added_monitors!(nodes[0], 1);
3835                                         }
3836                                 }
3837                         }
3838                 }
3839         }
3840
3841         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3842         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3843         if messages_delivered < 2 {
3844                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3845                 if messages_delivered < 1 {
3846                         expect_payment_sent!(nodes[0], payment_preimage_1);
3847                 } else {
3848                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3849                 }
3850         } else if messages_delivered == 2 {
3851                 // nodes[0] still wants its RAA + commitment_signed
3852                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3853         } else if messages_delivered == 3 {
3854                 // nodes[0] still wants its commitment_signed
3855                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3856         } else if messages_delivered == 4 {
3857                 // nodes[1] still wants its final RAA
3858                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3859         } else if messages_delivered == 5 {
3860                 // Everything was delivered...
3861                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3862         }
3863
3864         if messages_delivered == 1 || messages_delivered == 2 {
3865                 expect_payment_path_successful!(nodes[0]);
3866         }
3867         if messages_delivered <= 5 {
3868                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3869                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3870         }
3871         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3872
3873         if messages_delivered > 2 {
3874                 expect_payment_path_successful!(nodes[0]);
3875         }
3876
3877         // Channel should still work fine...
3878         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3879         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3880         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3881 }
3882
3883 #[test]
3884 fn test_drop_messages_peer_disconnect_a() {
3885         do_test_drop_messages_peer_disconnect(0, true);
3886         do_test_drop_messages_peer_disconnect(0, false);
3887         do_test_drop_messages_peer_disconnect(1, false);
3888         do_test_drop_messages_peer_disconnect(2, false);
3889 }
3890
3891 #[test]
3892 fn test_drop_messages_peer_disconnect_b() {
3893         do_test_drop_messages_peer_disconnect(3, false);
3894         do_test_drop_messages_peer_disconnect(4, false);
3895         do_test_drop_messages_peer_disconnect(5, false);
3896         do_test_drop_messages_peer_disconnect(6, false);
3897 }
3898
3899 #[test]
3900 fn test_channel_ready_without_best_block_updated() {
3901         // Previously, if we were offline when a funding transaction was locked in, and then we came
3902         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3903         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3904         // channel_ready immediately instead.
3905         let chanmon_cfgs = create_chanmon_cfgs(2);
3906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3908         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3909         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3910
3911         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3912
3913         let conf_height = nodes[0].best_block_info().1 + 1;
3914         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3915         let block_txn = [funding_tx];
3916         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3917         let conf_block_header = nodes[0].get_block_header(conf_height);
3918         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3919
3920         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3921         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3922         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3923 }
3924
3925 #[test]
3926 fn test_drop_messages_peer_disconnect_dual_htlc() {
3927         // Test that we can handle reconnecting when both sides of a channel have pending
3928         // commitment_updates when we disconnect.
3929         let chanmon_cfgs = create_chanmon_cfgs(2);
3930         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3931         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3932         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3933         create_announced_chan_between_nodes(&nodes, 0, 1);
3934
3935         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3936
3937         // Now try to send a second payment which will fail to send
3938         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3939         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3940         check_added_monitors!(nodes[0], 1);
3941
3942         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3943         assert_eq!(events_1.len(), 1);
3944         match events_1[0] {
3945                 MessageSendEvent::UpdateHTLCs { .. } => {},
3946                 _ => panic!("Unexpected event"),
3947         }
3948
3949         nodes[1].node.claim_funds(payment_preimage_1);
3950         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3951         check_added_monitors!(nodes[1], 1);
3952
3953         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3954         assert_eq!(events_2.len(), 1);
3955         match events_2[0] {
3956                 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 } } => {
3957                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3958                         assert!(update_add_htlcs.is_empty());
3959                         assert_eq!(update_fulfill_htlcs.len(), 1);
3960                         assert!(update_fail_htlcs.is_empty());
3961                         assert!(update_fail_malformed_htlcs.is_empty());
3962                         assert!(update_fee.is_none());
3963
3964                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3965                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3966                         assert_eq!(events_3.len(), 1);
3967                         match events_3[0] {
3968                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3969                                         assert_eq!(*payment_preimage, payment_preimage_1);
3970                                         assert_eq!(*payment_hash, payment_hash_1);
3971                                 },
3972                                 _ => panic!("Unexpected event"),
3973                         }
3974
3975                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3976                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3977                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3978                         check_added_monitors!(nodes[0], 1);
3979                 },
3980                 _ => panic!("Unexpected event"),
3981         }
3982
3983         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3984         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3985
3986         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
3987         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3988         assert_eq!(reestablish_1.len(), 1);
3989         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
3990         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3991         assert_eq!(reestablish_2.len(), 1);
3992
3993         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3994         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3995         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3996         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3997
3998         assert!(as_resp.0.is_none());
3999         assert!(bs_resp.0.is_none());
4000
4001         assert!(bs_resp.1.is_none());
4002         assert!(bs_resp.2.is_none());
4003
4004         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4005
4006         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4007         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4008         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4009         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4010         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4011         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4012         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4013         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4014         // No commitment_signed so get_event_msg's assert(len == 1) passes
4015         check_added_monitors!(nodes[1], 1);
4016
4017         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4018         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4019         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4020         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4021         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4022         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4023         assert!(bs_second_commitment_signed.update_fee.is_none());
4024         check_added_monitors!(nodes[1], 1);
4025
4026         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4027         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4028         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4029         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4030         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4031         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4032         assert!(as_commitment_signed.update_fee.is_none());
4033         check_added_monitors!(nodes[0], 1);
4034
4035         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4036         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4037         // No commitment_signed so get_event_msg's assert(len == 1) passes
4038         check_added_monitors!(nodes[0], 1);
4039
4040         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4041         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4042         // No commitment_signed so get_event_msg's assert(len == 1) passes
4043         check_added_monitors!(nodes[1], 1);
4044
4045         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4046         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4047         check_added_monitors!(nodes[1], 1);
4048
4049         expect_pending_htlcs_forwardable!(nodes[1]);
4050
4051         let events_5 = nodes[1].node.get_and_clear_pending_events();
4052         assert_eq!(events_5.len(), 1);
4053         match events_5[0] {
4054                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4055                         assert_eq!(payment_hash_2, *payment_hash);
4056                         match &purpose {
4057                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4058                                         assert!(payment_preimage.is_none());
4059                                         assert_eq!(payment_secret_2, *payment_secret);
4060                                 },
4061                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4062                         }
4063                 },
4064                 _ => panic!("Unexpected event"),
4065         }
4066
4067         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4068         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4069         check_added_monitors!(nodes[0], 1);
4070
4071         expect_payment_path_successful!(nodes[0]);
4072         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4073 }
4074
4075 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4076         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4077         // to avoid our counterparty failing the channel.
4078         let chanmon_cfgs = create_chanmon_cfgs(2);
4079         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4080         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4081         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4082
4083         create_announced_chan_between_nodes(&nodes, 0, 1);
4084
4085         let our_payment_hash = if send_partial_mpp {
4086                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4087                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4088                 // indicates there are more HTLCs coming.
4089                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4090                 let payment_id = PaymentId([42; 32]);
4091                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4092                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
4093                 check_added_monitors!(nodes[0], 1);
4094                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4095                 assert_eq!(events.len(), 1);
4096                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4097                 // hop should *not* yet generate any PaymentClaimable event(s).
4098                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4099                 our_payment_hash
4100         } else {
4101                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4102         };
4103
4104         let mut block = Block {
4105                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4106                 txdata: vec![],
4107         };
4108         connect_block(&nodes[0], &block);
4109         connect_block(&nodes[1], &block);
4110         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4111         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4112                 block.header.prev_blockhash = block.block_hash();
4113                 connect_block(&nodes[0], &block);
4114                 connect_block(&nodes[1], &block);
4115         }
4116
4117         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4118
4119         check_added_monitors!(nodes[1], 1);
4120         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4121         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4122         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4123         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4124         assert!(htlc_timeout_updates.update_fee.is_none());
4125
4126         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4127         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4128         // 100_000 msat as u64, followed by the height at which we failed back above
4129         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4130         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4131         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4132 }
4133
4134 #[test]
4135 fn test_htlc_timeout() {
4136         do_test_htlc_timeout(true);
4137         do_test_htlc_timeout(false);
4138 }
4139
4140 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4141         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4142         let chanmon_cfgs = create_chanmon_cfgs(3);
4143         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4144         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4145         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4146         create_announced_chan_between_nodes(&nodes, 0, 1);
4147         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4148
4149         // Make sure all nodes are at the same starting height
4150         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4151         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4152         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4153
4154         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4155         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4156         {
4157                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4158         }
4159         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4160         check_added_monitors!(nodes[1], 1);
4161
4162         // Now attempt to route a second payment, which should be placed in the holding cell
4163         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4164         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4165         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4166         if forwarded_htlc {
4167                 check_added_monitors!(nodes[0], 1);
4168                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4169                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4170                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4171                 expect_pending_htlcs_forwardable!(nodes[1]);
4172         }
4173         check_added_monitors!(nodes[1], 0);
4174
4175         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4176         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4177         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4178         connect_blocks(&nodes[1], 1);
4179
4180         if forwarded_htlc {
4181                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4182                 check_added_monitors!(nodes[1], 1);
4183                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4184                 assert_eq!(fail_commit.len(), 1);
4185                 match fail_commit[0] {
4186                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4187                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4188                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4189                         },
4190                         _ => unreachable!(),
4191                 }
4192                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4193         } else {
4194                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4195         }
4196 }
4197
4198 #[test]
4199 fn test_holding_cell_htlc_add_timeouts() {
4200         do_test_holding_cell_htlc_add_timeouts(false);
4201         do_test_holding_cell_htlc_add_timeouts(true);
4202 }
4203
4204 macro_rules! check_spendable_outputs {
4205         ($node: expr, $keysinterface: expr) => {
4206                 {
4207                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4208                         let mut txn = Vec::new();
4209                         let mut all_outputs = Vec::new();
4210                         let secp_ctx = Secp256k1::new();
4211                         for event in events.drain(..) {
4212                                 match event {
4213                                         Event::SpendableOutputs { mut outputs } => {
4214                                                 for outp in outputs.drain(..) {
4215                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4216                                                         all_outputs.push(outp);
4217                                                 }
4218                                         },
4219                                         _ => panic!("Unexpected event"),
4220                                 };
4221                         }
4222                         if all_outputs.len() > 1 {
4223                                 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx) {
4224                                         txn.push(tx);
4225                                 }
4226                         }
4227                         txn
4228                 }
4229         }
4230 }
4231
4232 #[test]
4233 fn test_claim_sizeable_push_msat() {
4234         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4235         let chanmon_cfgs = create_chanmon_cfgs(2);
4236         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4237         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4238         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4239
4240         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4241         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4242         check_closed_broadcast!(nodes[1], true);
4243         check_added_monitors!(nodes[1], 1);
4244         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4245         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4246         assert_eq!(node_txn.len(), 1);
4247         check_spends!(node_txn[0], chan.3);
4248         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
4249
4250         mine_transaction(&nodes[1], &node_txn[0]);
4251         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4252
4253         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4254         assert_eq!(spend_txn.len(), 1);
4255         assert_eq!(spend_txn[0].input.len(), 1);
4256         check_spends!(spend_txn[0], node_txn[0]);
4257         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4258 }
4259
4260 #[test]
4261 fn test_claim_on_remote_sizeable_push_msat() {
4262         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4263         // to_remote output is encumbered by a P2WPKH
4264         let chanmon_cfgs = create_chanmon_cfgs(2);
4265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4267         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4268
4269         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4270         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4271         check_closed_broadcast!(nodes[0], true);
4272         check_added_monitors!(nodes[0], 1);
4273         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4274
4275         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4276         assert_eq!(node_txn.len(), 1);
4277         check_spends!(node_txn[0], chan.3);
4278         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
4279
4280         mine_transaction(&nodes[1], &node_txn[0]);
4281         check_closed_broadcast!(nodes[1], true);
4282         check_added_monitors!(nodes[1], 1);
4283         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4284         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4285
4286         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4287         assert_eq!(spend_txn.len(), 1);
4288         check_spends!(spend_txn[0], node_txn[0]);
4289 }
4290
4291 #[test]
4292 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4293         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4294         // to_remote output is encumbered by a P2WPKH
4295
4296         let chanmon_cfgs = create_chanmon_cfgs(2);
4297         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4298         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4299         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4300
4301         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4302         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4303         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4304         assert_eq!(revoked_local_txn[0].input.len(), 1);
4305         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4306
4307         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4308         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4309         check_closed_broadcast!(nodes[1], true);
4310         check_added_monitors!(nodes[1], 1);
4311         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4312
4313         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4314         mine_transaction(&nodes[1], &node_txn[0]);
4315         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4316
4317         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4318         assert_eq!(spend_txn.len(), 3);
4319         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4320         check_spends!(spend_txn[1], node_txn[0]);
4321         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4322 }
4323
4324 #[test]
4325 fn test_static_spendable_outputs_preimage_tx() {
4326         let chanmon_cfgs = create_chanmon_cfgs(2);
4327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4329         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4330
4331         // Create some initial channels
4332         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4333
4334         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4335
4336         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4337         assert_eq!(commitment_tx[0].input.len(), 1);
4338         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4339
4340         // Settle A's commitment tx on B's chain
4341         nodes[1].node.claim_funds(payment_preimage);
4342         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4343         check_added_monitors!(nodes[1], 1);
4344         mine_transaction(&nodes[1], &commitment_tx[0]);
4345         check_added_monitors!(nodes[1], 1);
4346         let events = nodes[1].node.get_and_clear_pending_msg_events();
4347         match events[0] {
4348                 MessageSendEvent::UpdateHTLCs { .. } => {},
4349                 _ => panic!("Unexpected event"),
4350         }
4351         match events[1] {
4352                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4353                 _ => panic!("Unexepected event"),
4354         }
4355
4356         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4357         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4358         assert_eq!(node_txn.len(), 1);
4359         check_spends!(node_txn[0], commitment_tx[0]);
4360         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4361
4362         mine_transaction(&nodes[1], &node_txn[0]);
4363         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4364         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4365
4366         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4367         assert_eq!(spend_txn.len(), 1);
4368         check_spends!(spend_txn[0], node_txn[0]);
4369 }
4370
4371 #[test]
4372 fn test_static_spendable_outputs_timeout_tx() {
4373         let chanmon_cfgs = create_chanmon_cfgs(2);
4374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4377
4378         // Create some initial channels
4379         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4380
4381         // Rebalance the network a bit by relaying one payment through all the channels ...
4382         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4383
4384         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4385
4386         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4387         assert_eq!(commitment_tx[0].input.len(), 1);
4388         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4389
4390         // Settle A's commitment tx on B' chain
4391         mine_transaction(&nodes[1], &commitment_tx[0]);
4392         check_added_monitors!(nodes[1], 1);
4393         let events = nodes[1].node.get_and_clear_pending_msg_events();
4394         match events[0] {
4395                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4396                 _ => panic!("Unexpected event"),
4397         }
4398         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4399
4400         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4401         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4402         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4403         check_spends!(node_txn[0],  commitment_tx[0].clone());
4404         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4405
4406         mine_transaction(&nodes[1], &node_txn[0]);
4407         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4408         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4409         expect_payment_failed!(nodes[1], our_payment_hash, false);
4410
4411         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4412         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4413         check_spends!(spend_txn[0], commitment_tx[0]);
4414         check_spends!(spend_txn[1], node_txn[0]);
4415         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4416 }
4417
4418 #[test]
4419 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4420         let chanmon_cfgs = create_chanmon_cfgs(2);
4421         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4422         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4423         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4424
4425         // Create some initial channels
4426         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4427
4428         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4429         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4430         assert_eq!(revoked_local_txn[0].input.len(), 1);
4431         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4432
4433         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4434
4435         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4436         check_closed_broadcast!(nodes[1], true);
4437         check_added_monitors!(nodes[1], 1);
4438         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4439
4440         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4441         assert_eq!(node_txn.len(), 1);
4442         assert_eq!(node_txn[0].input.len(), 2);
4443         check_spends!(node_txn[0], revoked_local_txn[0]);
4444
4445         mine_transaction(&nodes[1], &node_txn[0]);
4446         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4447
4448         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4449         assert_eq!(spend_txn.len(), 1);
4450         check_spends!(spend_txn[0], node_txn[0]);
4451 }
4452
4453 #[test]
4454 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4455         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4456         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4457         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4458         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4459         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4460
4461         // Create some initial channels
4462         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4463
4464         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4465         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4466         assert_eq!(revoked_local_txn[0].input.len(), 1);
4467         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4468
4469         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4470
4471         // A will generate HTLC-Timeout from revoked commitment tx
4472         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4473         check_closed_broadcast!(nodes[0], true);
4474         check_added_monitors!(nodes[0], 1);
4475         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4476         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4477
4478         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4479         assert_eq!(revoked_htlc_txn.len(), 1);
4480         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4481         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4482         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4483         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4484
4485         // B will generate justice tx from A's revoked commitment/HTLC tx
4486         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4487         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4488         check_closed_broadcast!(nodes[1], true);
4489         check_added_monitors!(nodes[1], 1);
4490         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4491
4492         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4493         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4494         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4495         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4496         // transactions next...
4497         assert_eq!(node_txn[0].input.len(), 3);
4498         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4499
4500         assert_eq!(node_txn[1].input.len(), 2);
4501         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4502         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4503                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4504         } else {
4505                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4506                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4507         }
4508
4509         mine_transaction(&nodes[1], &node_txn[1]);
4510         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4511
4512         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4513         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4514         assert_eq!(spend_txn.len(), 1);
4515         assert_eq!(spend_txn[0].input.len(), 1);
4516         check_spends!(spend_txn[0], node_txn[1]);
4517 }
4518
4519 #[test]
4520 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4521         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4522         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4525         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4526
4527         // Create some initial channels
4528         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4529
4530         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4531         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4532         assert_eq!(revoked_local_txn[0].input.len(), 1);
4533         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4534
4535         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4536         assert_eq!(revoked_local_txn[0].output.len(), 2);
4537
4538         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4539
4540         // B will generate HTLC-Success from revoked commitment tx
4541         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4542         check_closed_broadcast!(nodes[1], true);
4543         check_added_monitors!(nodes[1], 1);
4544         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4545         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4546
4547         assert_eq!(revoked_htlc_txn.len(), 1);
4548         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4549         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4550         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4551
4552         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4553         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4554         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4555
4556         // A will generate justice tx from B's revoked commitment/HTLC tx
4557         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4558         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4559         check_closed_broadcast!(nodes[0], true);
4560         check_added_monitors!(nodes[0], 1);
4561         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4562
4563         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4564         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4565
4566         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4567         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4568         // transactions next...
4569         assert_eq!(node_txn[0].input.len(), 2);
4570         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4571         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4572                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4573         } else {
4574                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4575                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4576         }
4577
4578         assert_eq!(node_txn[1].input.len(), 1);
4579         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4580
4581         mine_transaction(&nodes[0], &node_txn[1]);
4582         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4583
4584         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4585         // didn't try to generate any new transactions.
4586
4587         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4588         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4589         assert_eq!(spend_txn.len(), 3);
4590         assert_eq!(spend_txn[0].input.len(), 1);
4591         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4592         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4593         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4594         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4595 }
4596
4597 #[test]
4598 fn test_onchain_to_onchain_claim() {
4599         // Test that in case of channel closure, we detect the state of output and claim HTLC
4600         // on downstream peer's remote commitment tx.
4601         // First, have C claim an HTLC against its own latest commitment transaction.
4602         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4603         // channel.
4604         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4605         // gets broadcast.
4606
4607         let chanmon_cfgs = create_chanmon_cfgs(3);
4608         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4609         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4610         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4611
4612         // Create some initial channels
4613         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4614         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4615
4616         // Ensure all nodes are at the same height
4617         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4618         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4619         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4620         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4621
4622         // Rebalance the network a bit by relaying one payment through all the channels ...
4623         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4624         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4625
4626         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4627         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4628         check_spends!(commitment_tx[0], chan_2.3);
4629         nodes[2].node.claim_funds(payment_preimage);
4630         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4631         check_added_monitors!(nodes[2], 1);
4632         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4633         assert!(updates.update_add_htlcs.is_empty());
4634         assert!(updates.update_fail_htlcs.is_empty());
4635         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4636         assert!(updates.update_fail_malformed_htlcs.is_empty());
4637
4638         mine_transaction(&nodes[2], &commitment_tx[0]);
4639         check_closed_broadcast!(nodes[2], true);
4640         check_added_monitors!(nodes[2], 1);
4641         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4642
4643         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4644         assert_eq!(c_txn.len(), 1);
4645         check_spends!(c_txn[0], commitment_tx[0]);
4646         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4647         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4648         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4649
4650         // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
4651         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4652         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4653         check_added_monitors!(nodes[1], 1);
4654         let events = nodes[1].node.get_and_clear_pending_events();
4655         assert_eq!(events.len(), 2);
4656         match events[0] {
4657                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4658                 _ => panic!("Unexpected event"),
4659         }
4660         match events[1] {
4661                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4662                         assert_eq!(fee_earned_msat, Some(1000));
4663                         assert_eq!(prev_channel_id, Some(chan_1.2));
4664                         assert_eq!(claim_from_onchain_tx, true);
4665                         assert_eq!(next_channel_id, Some(chan_2.2));
4666                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4667                 },
4668                 _ => panic!("Unexpected event"),
4669         }
4670         check_added_monitors!(nodes[1], 1);
4671         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4672         assert_eq!(msg_events.len(), 3);
4673         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4674         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4675
4676         match nodes_2_event {
4677                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4678                 _ => panic!("Unexpected event"),
4679         }
4680
4681         match nodes_0_event {
4682                 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, .. } } => {
4683                         assert!(update_add_htlcs.is_empty());
4684                         assert!(update_fail_htlcs.is_empty());
4685                         assert_eq!(update_fulfill_htlcs.len(), 1);
4686                         assert!(update_fail_malformed_htlcs.is_empty());
4687                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4688                 },
4689                 _ => panic!("Unexpected event"),
4690         };
4691
4692         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4693         match msg_events[0] {
4694                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4695                 _ => panic!("Unexpected event"),
4696         }
4697
4698         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4699         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4700         mine_transaction(&nodes[1], &commitment_tx[0]);
4701         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4702         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4703         // ChannelMonitor: HTLC-Success tx
4704         assert_eq!(b_txn.len(), 1);
4705         check_spends!(b_txn[0], commitment_tx[0]);
4706         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4707         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4708         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4709
4710         check_closed_broadcast!(nodes[1], true);
4711         check_added_monitors!(nodes[1], 1);
4712 }
4713
4714 #[test]
4715 fn test_duplicate_payment_hash_one_failure_one_success() {
4716         // Topology : A --> B --> C --> D
4717         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4718         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4719         // we forward one of the payments onwards to D.
4720         let chanmon_cfgs = create_chanmon_cfgs(4);
4721         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4722         // When this test was written, the default base fee floated based on the HTLC count.
4723         // It is now fixed, so we simply set the fee to the expected value here.
4724         let mut config = test_default_channel_config();
4725         config.channel_config.forwarding_fee_base_msat = 196;
4726         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4727                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4728         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4729
4730         create_announced_chan_between_nodes(&nodes, 0, 1);
4731         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4732         create_announced_chan_between_nodes(&nodes, 2, 3);
4733
4734         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4735         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4736         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4737         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4738         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4739
4740         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4741
4742         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4743         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4744         // script push size limit so that the below script length checks match
4745         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4746         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4747                 .with_features(nodes[3].node.invoice_features());
4748         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4749         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4750
4751         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4752         assert_eq!(commitment_txn[0].input.len(), 1);
4753         check_spends!(commitment_txn[0], chan_2.3);
4754
4755         mine_transaction(&nodes[1], &commitment_txn[0]);
4756         check_closed_broadcast!(nodes[1], true);
4757         check_added_monitors!(nodes[1], 1);
4758         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4759         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4760
4761         let htlc_timeout_tx;
4762         { // Extract one of the two HTLC-Timeout transaction
4763                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4764                 // ChannelMonitor: timeout tx * 2-or-3
4765                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4766
4767                 check_spends!(node_txn[0], commitment_txn[0]);
4768                 assert_eq!(node_txn[0].input.len(), 1);
4769                 assert_eq!(node_txn[0].output.len(), 1);
4770
4771                 if node_txn.len() > 2 {
4772                         check_spends!(node_txn[1], commitment_txn[0]);
4773                         assert_eq!(node_txn[1].input.len(), 1);
4774                         assert_eq!(node_txn[1].output.len(), 1);
4775                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4776
4777                         check_spends!(node_txn[2], commitment_txn[0]);
4778                         assert_eq!(node_txn[2].input.len(), 1);
4779                         assert_eq!(node_txn[2].output.len(), 1);
4780                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4781                 } else {
4782                         check_spends!(node_txn[1], commitment_txn[0]);
4783                         assert_eq!(node_txn[1].input.len(), 1);
4784                         assert_eq!(node_txn[1].output.len(), 1);
4785                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4786                 }
4787
4788                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4789                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4790                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4791                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4792                 if node_txn.len() > 2 {
4793                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4794                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4795                 } else {
4796                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4797                 }
4798         }
4799
4800         nodes[2].node.claim_funds(our_payment_preimage);
4801         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4802
4803         mine_transaction(&nodes[2], &commitment_txn[0]);
4804         check_added_monitors!(nodes[2], 2);
4805         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4806         let events = nodes[2].node.get_and_clear_pending_msg_events();
4807         match events[0] {
4808                 MessageSendEvent::UpdateHTLCs { .. } => {},
4809                 _ => panic!("Unexpected event"),
4810         }
4811         match events[1] {
4812                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4813                 _ => panic!("Unexepected event"),
4814         }
4815         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4816         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4817         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4818         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4819         assert_eq!(htlc_success_txn[0].input.len(), 1);
4820         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4821         assert_eq!(htlc_success_txn[1].input.len(), 1);
4822         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4823         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4824         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4825
4826         mine_transaction(&nodes[1], &htlc_timeout_tx);
4827         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4828         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4829         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4830         assert!(htlc_updates.update_add_htlcs.is_empty());
4831         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4832         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4833         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4834         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4835         check_added_monitors!(nodes[1], 1);
4836
4837         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4838         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4839         {
4840                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4841         }
4842         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4843
4844         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4845         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4846         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4847         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4848         assert!(updates.update_add_htlcs.is_empty());
4849         assert!(updates.update_fail_htlcs.is_empty());
4850         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4851         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4852         assert!(updates.update_fail_malformed_htlcs.is_empty());
4853         check_added_monitors!(nodes[1], 1);
4854
4855         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4856         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4857
4858         let events = nodes[0].node.get_and_clear_pending_events();
4859         match events[0] {
4860                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4861                         assert_eq!(*payment_preimage, our_payment_preimage);
4862                         assert_eq!(*payment_hash, duplicate_payment_hash);
4863                 }
4864                 _ => panic!("Unexpected event"),
4865         }
4866 }
4867
4868 #[test]
4869 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4870         let chanmon_cfgs = create_chanmon_cfgs(2);
4871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4873         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4874
4875         // Create some initial channels
4876         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4877
4878         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4879         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4880         assert_eq!(local_txn.len(), 1);
4881         assert_eq!(local_txn[0].input.len(), 1);
4882         check_spends!(local_txn[0], chan_1.3);
4883
4884         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4885         nodes[1].node.claim_funds(payment_preimage);
4886         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4887         check_added_monitors!(nodes[1], 1);
4888
4889         mine_transaction(&nodes[1], &local_txn[0]);
4890         check_added_monitors!(nodes[1], 1);
4891         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4892         let events = nodes[1].node.get_and_clear_pending_msg_events();
4893         match events[0] {
4894                 MessageSendEvent::UpdateHTLCs { .. } => {},
4895                 _ => panic!("Unexpected event"),
4896         }
4897         match events[1] {
4898                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4899                 _ => panic!("Unexepected event"),
4900         }
4901         let node_tx = {
4902                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4903                 assert_eq!(node_txn.len(), 1);
4904                 assert_eq!(node_txn[0].input.len(), 1);
4905                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4906                 check_spends!(node_txn[0], local_txn[0]);
4907                 node_txn[0].clone()
4908         };
4909
4910         mine_transaction(&nodes[1], &node_tx);
4911         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4912
4913         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4914         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4915         assert_eq!(spend_txn.len(), 1);
4916         assert_eq!(spend_txn[0].input.len(), 1);
4917         check_spends!(spend_txn[0], node_tx);
4918         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4919 }
4920
4921 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4922         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4923         // unrevoked commitment transaction.
4924         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4925         // a remote RAA before they could be failed backwards (and combinations thereof).
4926         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4927         // use the same payment hashes.
4928         // Thus, we use a six-node network:
4929         //
4930         // A \         / E
4931         //    - C - D -
4932         // B /         \ F
4933         // And test where C fails back to A/B when D announces its latest commitment transaction
4934         let chanmon_cfgs = create_chanmon_cfgs(6);
4935         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4936         // When this test was written, the default base fee floated based on the HTLC count.
4937         // It is now fixed, so we simply set the fee to the expected value here.
4938         let mut config = test_default_channel_config();
4939         config.channel_config.forwarding_fee_base_msat = 196;
4940         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4941                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4942         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4943
4944         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4945         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4946         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4947         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4948         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4949
4950         // Rebalance and check output sanity...
4951         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4952         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4953         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4954
4955         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4956                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4957         // 0th HTLC:
4958         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
4959         // 1st HTLC:
4960         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
4961         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4962         // 2nd HTLC:
4963         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4964         // 3rd HTLC:
4965         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4966         // 4th HTLC:
4967         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4968         // 5th HTLC:
4969         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4970         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4971         // 6th HTLC:
4972         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
4973         // 7th HTLC:
4974         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
4975
4976         // 8th HTLC:
4977         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4978         // 9th HTLC:
4979         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4980         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4981
4982         // 10th HTLC:
4983         let (_, payment_hash_6, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
4984         // 11th HTLC:
4985         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4986         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
4987
4988         // Double-check that six of the new HTLC were added
4989         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4990         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4991         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4992         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4993
4994         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4995         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4996         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4997         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4998         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4999         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5000         check_added_monitors!(nodes[4], 0);
5001
5002         let failed_destinations = vec![
5003                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5004                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5005                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5006                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5007         ];
5008         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5009         check_added_monitors!(nodes[4], 1);
5010
5011         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5012         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5013         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5014         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5015         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5016         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5017
5018         // Fail 3rd below-dust and 7th above-dust HTLCs
5019         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5020         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5021         check_added_monitors!(nodes[5], 0);
5022
5023         let failed_destinations_2 = vec![
5024                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5025                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5026         ];
5027         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5028         check_added_monitors!(nodes[5], 1);
5029
5030         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5031         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5032         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5033         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5034
5035         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5036
5037         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5038         let failed_destinations_3 = vec![
5039                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5040                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5041                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5042                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5043                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5044                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5045         ];
5046         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5047         check_added_monitors!(nodes[3], 1);
5048         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5049         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5050         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5051         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5052         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5053         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5054         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5055         if deliver_last_raa {
5056                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5057         } else {
5058                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5059         }
5060
5061         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5062         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5063         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5064         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5065         //
5066         // We now broadcast the latest commitment transaction, which *should* result in failures for
5067         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5068         // the non-broadcast above-dust HTLCs.
5069         //
5070         // Alternatively, we may broadcast the previous commitment transaction, which should only
5071         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5072         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5073
5074         if announce_latest {
5075                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5076         } else {
5077                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5078         }
5079         let events = nodes[2].node.get_and_clear_pending_events();
5080         let close_event = if deliver_last_raa {
5081                 assert_eq!(events.len(), 2 + 6);
5082                 events.last().clone().unwrap()
5083         } else {
5084                 assert_eq!(events.len(), 1);
5085                 events.last().clone().unwrap()
5086         };
5087         match close_event {
5088                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5089                 _ => panic!("Unexpected event"),
5090         }
5091
5092         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5093         check_closed_broadcast!(nodes[2], true);
5094         if deliver_last_raa {
5095                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5096
5097                 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5098                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5099         } else {
5100                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5101                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5102                 } else {
5103                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5104                 };
5105
5106                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5107         }
5108         check_added_monitors!(nodes[2], 3);
5109
5110         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5111         assert_eq!(cs_msgs.len(), 2);
5112         let mut a_done = false;
5113         for msg in cs_msgs {
5114                 match msg {
5115                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5116                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5117                                 // should be failed-backwards here.
5118                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5119                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5120                                         for htlc in &updates.update_fail_htlcs {
5121                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5122                                         }
5123                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5124                                         assert!(!a_done);
5125                                         a_done = true;
5126                                         &nodes[0]
5127                                 } else {
5128                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5129                                         for htlc in &updates.update_fail_htlcs {
5130                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5131                                         }
5132                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5133                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5134                                         &nodes[1]
5135                                 };
5136                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5137                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5138                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5139                                 if announce_latest {
5140                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5141                                         if *node_id == nodes[0].node.get_our_node_id() {
5142                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5143                                         }
5144                                 }
5145                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5146                         },
5147                         _ => panic!("Unexpected event"),
5148                 }
5149         }
5150
5151         let as_events = nodes[0].node.get_and_clear_pending_events();
5152         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5153         let mut as_failds = HashSet::new();
5154         let mut as_updates = 0;
5155         for event in as_events.iter() {
5156                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5157                         assert!(as_failds.insert(*payment_hash));
5158                         if *payment_hash != payment_hash_2 {
5159                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5160                         } else {
5161                                 assert!(!payment_failed_permanently);
5162                         }
5163                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5164                                 as_updates += 1;
5165                         }
5166                 } else if let &Event::PaymentFailed { .. } = event {
5167                 } else { panic!("Unexpected event"); }
5168         }
5169         assert!(as_failds.contains(&payment_hash_1));
5170         assert!(as_failds.contains(&payment_hash_2));
5171         if announce_latest {
5172                 assert!(as_failds.contains(&payment_hash_3));
5173                 assert!(as_failds.contains(&payment_hash_5));
5174         }
5175         assert!(as_failds.contains(&payment_hash_6));
5176
5177         let bs_events = nodes[1].node.get_and_clear_pending_events();
5178         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5179         let mut bs_failds = HashSet::new();
5180         let mut bs_updates = 0;
5181         for event in bs_events.iter() {
5182                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5183                         assert!(bs_failds.insert(*payment_hash));
5184                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5185                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5186                         } else {
5187                                 assert!(!payment_failed_permanently);
5188                         }
5189                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5190                                 bs_updates += 1;
5191                         }
5192                 } else if let &Event::PaymentFailed { .. } = event {
5193                 } else { panic!("Unexpected event"); }
5194         }
5195         assert!(bs_failds.contains(&payment_hash_1));
5196         assert!(bs_failds.contains(&payment_hash_2));
5197         if announce_latest {
5198                 assert!(bs_failds.contains(&payment_hash_4));
5199         }
5200         assert!(bs_failds.contains(&payment_hash_5));
5201
5202         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5203         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5204         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5205         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5206         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5207         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5208 }
5209
5210 #[test]
5211 fn test_fail_backwards_latest_remote_announce_a() {
5212         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5213 }
5214
5215 #[test]
5216 fn test_fail_backwards_latest_remote_announce_b() {
5217         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5218 }
5219
5220 #[test]
5221 fn test_fail_backwards_previous_remote_announce() {
5222         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5223         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5224         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5225 }
5226
5227 #[test]
5228 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5229         let chanmon_cfgs = create_chanmon_cfgs(2);
5230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5233
5234         // Create some initial channels
5235         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5236
5237         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5238         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5239         assert_eq!(local_txn[0].input.len(), 1);
5240         check_spends!(local_txn[0], chan_1.3);
5241
5242         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5243         mine_transaction(&nodes[0], &local_txn[0]);
5244         check_closed_broadcast!(nodes[0], true);
5245         check_added_monitors!(nodes[0], 1);
5246         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5247         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5248
5249         let htlc_timeout = {
5250                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5251                 assert_eq!(node_txn.len(), 1);
5252                 assert_eq!(node_txn[0].input.len(), 1);
5253                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5254                 check_spends!(node_txn[0], local_txn[0]);
5255                 node_txn[0].clone()
5256         };
5257
5258         mine_transaction(&nodes[0], &htlc_timeout);
5259         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5260         expect_payment_failed!(nodes[0], our_payment_hash, false);
5261
5262         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5263         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5264         assert_eq!(spend_txn.len(), 3);
5265         check_spends!(spend_txn[0], local_txn[0]);
5266         assert_eq!(spend_txn[1].input.len(), 1);
5267         check_spends!(spend_txn[1], htlc_timeout);
5268         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5269         assert_eq!(spend_txn[2].input.len(), 2);
5270         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5271         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5272                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5273 }
5274
5275 #[test]
5276 fn test_key_derivation_params() {
5277         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5278         // manager rotation to test that `channel_keys_id` returned in
5279         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5280         // then derive a `delayed_payment_key`.
5281
5282         let chanmon_cfgs = create_chanmon_cfgs(3);
5283
5284         // We manually create the node configuration to backup the seed.
5285         let seed = [42; 32];
5286         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5287         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5288         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5289         let scorer = Mutex::new(test_utils::TestScorer::new());
5290         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5291         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5292         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5293         node_cfgs.remove(0);
5294         node_cfgs.insert(0, node);
5295
5296         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5297         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5298
5299         // Create some initial channels
5300         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5301         // for node 0
5302         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5303         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5304         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5305
5306         // Ensure all nodes are at the same height
5307         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5308         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5309         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5310         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5311
5312         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5313         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5314         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5315         assert_eq!(local_txn_1[0].input.len(), 1);
5316         check_spends!(local_txn_1[0], chan_1.3);
5317
5318         // We check funding pubkey are unique
5319         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5320         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5321         if from_0_funding_key_0 == from_1_funding_key_0
5322             || from_0_funding_key_0 == from_1_funding_key_1
5323             || from_0_funding_key_1 == from_1_funding_key_0
5324             || from_0_funding_key_1 == from_1_funding_key_1 {
5325                 panic!("Funding pubkeys aren't unique");
5326         }
5327
5328         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5329         mine_transaction(&nodes[0], &local_txn_1[0]);
5330         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5331         check_closed_broadcast!(nodes[0], true);
5332         check_added_monitors!(nodes[0], 1);
5333         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5334
5335         let htlc_timeout = {
5336                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5337                 assert_eq!(node_txn.len(), 1);
5338                 assert_eq!(node_txn[0].input.len(), 1);
5339                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5340                 check_spends!(node_txn[0], local_txn_1[0]);
5341                 node_txn[0].clone()
5342         };
5343
5344         mine_transaction(&nodes[0], &htlc_timeout);
5345         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5346         expect_payment_failed!(nodes[0], our_payment_hash, false);
5347
5348         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5349         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5350         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5351         assert_eq!(spend_txn.len(), 3);
5352         check_spends!(spend_txn[0], local_txn_1[0]);
5353         assert_eq!(spend_txn[1].input.len(), 1);
5354         check_spends!(spend_txn[1], htlc_timeout);
5355         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5356         assert_eq!(spend_txn[2].input.len(), 2);
5357         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5358         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5359                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5360 }
5361
5362 #[test]
5363 fn test_static_output_closing_tx() {
5364         let chanmon_cfgs = create_chanmon_cfgs(2);
5365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5367         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5368
5369         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5370
5371         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5372         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5373
5374         mine_transaction(&nodes[0], &closing_tx);
5375         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5376         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5377
5378         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5379         assert_eq!(spend_txn.len(), 1);
5380         check_spends!(spend_txn[0], closing_tx);
5381
5382         mine_transaction(&nodes[1], &closing_tx);
5383         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5384         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5385
5386         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5387         assert_eq!(spend_txn.len(), 1);
5388         check_spends!(spend_txn[0], closing_tx);
5389 }
5390
5391 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5392         let chanmon_cfgs = create_chanmon_cfgs(2);
5393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5395         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5396         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5397
5398         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5399
5400         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5401         // present in B's local commitment transaction, but none of A's commitment transactions.
5402         nodes[1].node.claim_funds(payment_preimage);
5403         check_added_monitors!(nodes[1], 1);
5404         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5405
5406         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5407         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5408         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5409
5410         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5411         check_added_monitors!(nodes[0], 1);
5412         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5413         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5414         check_added_monitors!(nodes[1], 1);
5415
5416         let starting_block = nodes[1].best_block_info();
5417         let mut block = Block {
5418                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5419                 txdata: vec![],
5420         };
5421         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5422                 connect_block(&nodes[1], &block);
5423                 block.header.prev_blockhash = block.block_hash();
5424         }
5425         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5426         check_closed_broadcast!(nodes[1], true);
5427         check_added_monitors!(nodes[1], 1);
5428         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5429 }
5430
5431 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5432         let chanmon_cfgs = create_chanmon_cfgs(2);
5433         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5434         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5435         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5436         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5437
5438         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5439         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5440         check_added_monitors!(nodes[0], 1);
5441
5442         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5443
5444         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5445         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5446         // to "time out" the HTLC.
5447
5448         let starting_block = nodes[1].best_block_info();
5449         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5450
5451         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5452                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5453                 header.prev_blockhash = header.block_hash();
5454         }
5455         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5456         check_closed_broadcast!(nodes[0], true);
5457         check_added_monitors!(nodes[0], 1);
5458         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5459 }
5460
5461 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5462         let chanmon_cfgs = create_chanmon_cfgs(3);
5463         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5464         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5465         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5466         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5467
5468         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5469         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5470         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5471         // actually revoked.
5472         let htlc_value = if use_dust { 50000 } else { 3000000 };
5473         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5474         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5475         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5476         check_added_monitors!(nodes[1], 1);
5477
5478         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5479         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5480         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5481         check_added_monitors!(nodes[0], 1);
5482         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5483         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5484         check_added_monitors!(nodes[1], 1);
5485         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5486         check_added_monitors!(nodes[1], 1);
5487         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5488
5489         if check_revoke_no_close {
5490                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5491                 check_added_monitors!(nodes[0], 1);
5492         }
5493
5494         let starting_block = nodes[1].best_block_info();
5495         let mut block = Block {
5496                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5497                 txdata: vec![],
5498         };
5499         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5500                 connect_block(&nodes[0], &block);
5501                 block.header.prev_blockhash = block.block_hash();
5502         }
5503         if !check_revoke_no_close {
5504                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5505                 check_closed_broadcast!(nodes[0], true);
5506                 check_added_monitors!(nodes[0], 1);
5507                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5508         } else {
5509                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5510         }
5511 }
5512
5513 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5514 // There are only a few cases to test here:
5515 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5516 //    broadcastable commitment transactions result in channel closure,
5517 //  * its included in an unrevoked-but-previous remote commitment transaction,
5518 //  * its included in the latest remote or local commitment transactions.
5519 // We test each of the three possible commitment transactions individually and use both dust and
5520 // non-dust HTLCs.
5521 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5522 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5523 // tested for at least one of the cases in other tests.
5524 #[test]
5525 fn htlc_claim_single_commitment_only_a() {
5526         do_htlc_claim_local_commitment_only(true);
5527         do_htlc_claim_local_commitment_only(false);
5528
5529         do_htlc_claim_current_remote_commitment_only(true);
5530         do_htlc_claim_current_remote_commitment_only(false);
5531 }
5532
5533 #[test]
5534 fn htlc_claim_single_commitment_only_b() {
5535         do_htlc_claim_previous_remote_commitment_only(true, false);
5536         do_htlc_claim_previous_remote_commitment_only(false, false);
5537         do_htlc_claim_previous_remote_commitment_only(true, true);
5538         do_htlc_claim_previous_remote_commitment_only(false, true);
5539 }
5540
5541 #[test]
5542 #[should_panic]
5543 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5544         let chanmon_cfgs = create_chanmon_cfgs(2);
5545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5548         // Force duplicate randomness for every get-random call
5549         for node in nodes.iter() {
5550                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5551         }
5552
5553         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5554         let channel_value_satoshis=10000;
5555         let push_msat=10001;
5556         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5557         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5558         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5559         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5560
5561         // Create a second channel with the same random values. This used to panic due to a colliding
5562         // channel_id, but now panics due to a colliding outbound SCID alias.
5563         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5564 }
5565
5566 #[test]
5567 fn bolt2_open_channel_sending_node_checks_part2() {
5568         let chanmon_cfgs = create_chanmon_cfgs(2);
5569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5572
5573         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5574         let channel_value_satoshis=2^24;
5575         let push_msat=10001;
5576         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5577
5578         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5579         let channel_value_satoshis=10000;
5580         // Test when push_msat is equal to 1000 * funding_satoshis.
5581         let push_msat=1000*channel_value_satoshis+1;
5582         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5583
5584         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5585         let channel_value_satoshis=10000;
5586         let push_msat=10001;
5587         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5588         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5589         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5590
5591         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5592         // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5593         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5594
5595         // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5596         assert!(BREAKDOWN_TIMEOUT>0);
5597         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5598
5599         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5600         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5601         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5602
5603         // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5604         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5605         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5606         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5607         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5608         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5609 }
5610
5611 #[test]
5612 fn bolt2_open_channel_sane_dust_limit() {
5613         let chanmon_cfgs = create_chanmon_cfgs(2);
5614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5616         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5617
5618         let channel_value_satoshis=1000000;
5619         let push_msat=10001;
5620         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5621         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5622         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5623         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5624
5625         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5626         let events = nodes[1].node.get_and_clear_pending_msg_events();
5627         let err_msg = match events[0] {
5628                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5629                         msg.clone()
5630                 },
5631                 _ => panic!("Unexpected event"),
5632         };
5633         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5634 }
5635
5636 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5637 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5638 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5639 // is no longer affordable once it's freed.
5640 #[test]
5641 fn test_fail_holding_cell_htlc_upon_free() {
5642         let chanmon_cfgs = create_chanmon_cfgs(2);
5643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5645         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5646         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5647
5648         // First nodes[0] generates an update_fee, setting the channel's
5649         // pending_update_fee.
5650         {
5651                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5652                 *feerate_lock += 20;
5653         }
5654         nodes[0].node.timer_tick_occurred();
5655         check_added_monitors!(nodes[0], 1);
5656
5657         let events = nodes[0].node.get_and_clear_pending_msg_events();
5658         assert_eq!(events.len(), 1);
5659         let (update_msg, commitment_signed) = match events[0] {
5660                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5661                         (update_fee.as_ref(), commitment_signed)
5662                 },
5663                 _ => panic!("Unexpected event"),
5664         };
5665
5666         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5667
5668         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5669         let channel_reserve = chan_stat.channel_reserve_msat;
5670         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5671         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5672
5673         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5674         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5675         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5676
5677         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5678         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5679         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5680         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5681
5682         // Flush the pending fee update.
5683         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5684         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5685         check_added_monitors!(nodes[1], 1);
5686         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5687         check_added_monitors!(nodes[0], 1);
5688
5689         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5690         // HTLC, but now that the fee has been raised the payment will now fail, causing
5691         // us to surface its failure to the user.
5692         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5693         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5694         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5695         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5696                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5697         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5698
5699         // Check that the payment failed to be sent out.
5700         let events = nodes[0].node.get_and_clear_pending_events();
5701         assert_eq!(events.len(), 2);
5702         match &events[0] {
5703                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5704                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5705                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5706                         assert_eq!(*payment_failed_permanently, false);
5707                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5708                 },
5709                 _ => panic!("Unexpected event"),
5710         }
5711         match &events[1] {
5712                 &Event::PaymentFailed { ref payment_hash, .. } => {
5713                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5714                 },
5715                 _ => panic!("Unexpected event"),
5716         }
5717 }
5718
5719 // Test that if multiple HTLCs are released from the holding cell and one is
5720 // valid but the other is no longer valid upon release, the valid HTLC can be
5721 // successfully completed while the other one fails as expected.
5722 #[test]
5723 fn test_free_and_fail_holding_cell_htlcs() {
5724         let chanmon_cfgs = create_chanmon_cfgs(2);
5725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5727         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5728         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5729
5730         // First nodes[0] generates an update_fee, setting the channel's
5731         // pending_update_fee.
5732         {
5733                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5734                 *feerate_lock += 200;
5735         }
5736         nodes[0].node.timer_tick_occurred();
5737         check_added_monitors!(nodes[0], 1);
5738
5739         let events = nodes[0].node.get_and_clear_pending_msg_events();
5740         assert_eq!(events.len(), 1);
5741         let (update_msg, commitment_signed) = match events[0] {
5742                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5743                         (update_fee.as_ref(), commitment_signed)
5744                 },
5745                 _ => panic!("Unexpected event"),
5746         };
5747
5748         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5749
5750         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5751         let channel_reserve = chan_stat.channel_reserve_msat;
5752         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5753         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5754
5755         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5756         let amt_1 = 20000;
5757         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5758         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5759         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5760
5761         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5762         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5763         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5764         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5765         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5766         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5767         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5768         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5769
5770         // Flush the pending fee update.
5771         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5772         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5773         check_added_monitors!(nodes[1], 1);
5774         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5775         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5776         check_added_monitors!(nodes[0], 2);
5777
5778         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5779         // but now that the fee has been raised the second payment will now fail, causing us
5780         // to surface its failure to the user. The first payment should succeed.
5781         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5782         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5783         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5784         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5785                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5786         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5787
5788         // Check that the second payment failed to be sent out.
5789         let events = nodes[0].node.get_and_clear_pending_events();
5790         assert_eq!(events.len(), 2);
5791         match &events[0] {
5792                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5793                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5794                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5795                         assert_eq!(*payment_failed_permanently, false);
5796                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5797                 },
5798                 _ => panic!("Unexpected event"),
5799         }
5800         match &events[1] {
5801                 &Event::PaymentFailed { ref payment_hash, .. } => {
5802                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5803                 },
5804                 _ => panic!("Unexpected event"),
5805         }
5806
5807         // Complete the first payment and the RAA from the fee update.
5808         let (payment_event, send_raa_event) = {
5809                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5810                 assert_eq!(msgs.len(), 2);
5811                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5812         };
5813         let raa = match send_raa_event {
5814                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5815                 _ => panic!("Unexpected event"),
5816         };
5817         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5818         check_added_monitors!(nodes[1], 1);
5819         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5820         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5821         let events = nodes[1].node.get_and_clear_pending_events();
5822         assert_eq!(events.len(), 1);
5823         match events[0] {
5824                 Event::PendingHTLCsForwardable { .. } => {},
5825                 _ => panic!("Unexpected event"),
5826         }
5827         nodes[1].node.process_pending_htlc_forwards();
5828         let events = nodes[1].node.get_and_clear_pending_events();
5829         assert_eq!(events.len(), 1);
5830         match events[0] {
5831                 Event::PaymentClaimable { .. } => {},
5832                 _ => panic!("Unexpected event"),
5833         }
5834         nodes[1].node.claim_funds(payment_preimage_1);
5835         check_added_monitors!(nodes[1], 1);
5836         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5837
5838         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5839         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5840         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5841         expect_payment_sent!(nodes[0], payment_preimage_1);
5842 }
5843
5844 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5845 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5846 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5847 // once it's freed.
5848 #[test]
5849 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5850         let chanmon_cfgs = create_chanmon_cfgs(3);
5851         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5852         // When this test was written, the default base fee floated based on the HTLC count.
5853         // It is now fixed, so we simply set the fee to the expected value here.
5854         let mut config = test_default_channel_config();
5855         config.channel_config.forwarding_fee_base_msat = 196;
5856         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5857         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5858         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5859         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5860
5861         // First nodes[1] generates an update_fee, setting the channel's
5862         // pending_update_fee.
5863         {
5864                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5865                 *feerate_lock += 20;
5866         }
5867         nodes[1].node.timer_tick_occurred();
5868         check_added_monitors!(nodes[1], 1);
5869
5870         let events = nodes[1].node.get_and_clear_pending_msg_events();
5871         assert_eq!(events.len(), 1);
5872         let (update_msg, commitment_signed) = match events[0] {
5873                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5874                         (update_fee.as_ref(), commitment_signed)
5875                 },
5876                 _ => panic!("Unexpected event"),
5877         };
5878
5879         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5880
5881         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5882         let channel_reserve = chan_stat.channel_reserve_msat;
5883         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5884         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5885
5886         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5887         let feemsat = 239;
5888         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5889         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5890         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5891         let payment_event = {
5892                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5893                 check_added_monitors!(nodes[0], 1);
5894
5895                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5896                 assert_eq!(events.len(), 1);
5897
5898                 SendEvent::from_event(events.remove(0))
5899         };
5900         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5901         check_added_monitors!(nodes[1], 0);
5902         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5903         expect_pending_htlcs_forwardable!(nodes[1]);
5904
5905         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5906         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5907
5908         // Flush the pending fee update.
5909         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5910         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5911         check_added_monitors!(nodes[2], 1);
5912         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5913         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5914         check_added_monitors!(nodes[1], 2);
5915
5916         // A final RAA message is generated to finalize the fee update.
5917         let events = nodes[1].node.get_and_clear_pending_msg_events();
5918         assert_eq!(events.len(), 1);
5919
5920         let raa_msg = match &events[0] {
5921                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5922                         msg.clone()
5923                 },
5924                 _ => panic!("Unexpected event"),
5925         };
5926
5927         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5928         check_added_monitors!(nodes[2], 1);
5929         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5930
5931         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5932         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5933         assert_eq!(process_htlc_forwards_event.len(), 2);
5934         match &process_htlc_forwards_event[0] {
5935                 &Event::PendingHTLCsForwardable { .. } => {},
5936                 _ => panic!("Unexpected event"),
5937         }
5938
5939         // In response, we call ChannelManager's process_pending_htlc_forwards
5940         nodes[1].node.process_pending_htlc_forwards();
5941         check_added_monitors!(nodes[1], 1);
5942
5943         // This causes the HTLC to be failed backwards.
5944         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5945         assert_eq!(fail_event.len(), 1);
5946         let (fail_msg, commitment_signed) = match &fail_event[0] {
5947                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5948                         assert_eq!(updates.update_add_htlcs.len(), 0);
5949                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5950                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5951                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5952                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5953                 },
5954                 _ => panic!("Unexpected event"),
5955         };
5956
5957         // Pass the failure messages back to nodes[0].
5958         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5959         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5960
5961         // Complete the HTLC failure+removal process.
5962         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5963         check_added_monitors!(nodes[0], 1);
5964         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5965         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5966         check_added_monitors!(nodes[1], 2);
5967         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5968         assert_eq!(final_raa_event.len(), 1);
5969         let raa = match &final_raa_event[0] {
5970                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5971                 _ => panic!("Unexpected event"),
5972         };
5973         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5974         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5975         check_added_monitors!(nodes[0], 1);
5976 }
5977
5978 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5979 // BOLT 2 Requirement: MUST NOT offer amount_msat it cannot pay for in the remote commitment transaction at the current feerate_per_kw (see "Updating Fees") while maintaining its channel reserve.
5980 //TODO: I don't believe this is explicitly enforced when sending an HTLC but as the Fee aspect of the BOLT specs is in flux leaving this as a TODO.
5981
5982 #[test]
5983 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5984         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5985         let chanmon_cfgs = create_chanmon_cfgs(2);
5986         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5987         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5988         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5989         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5990
5991         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5992         route.paths[0][0].fee_msat = 100;
5993
5994         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
5995                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5996         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5997         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
5998 }
5999
6000 #[test]
6001 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6002         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6003         let chanmon_cfgs = create_chanmon_cfgs(2);
6004         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6005         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6006         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6007         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6008
6009         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6010         route.paths[0][0].fee_msat = 0;
6011         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6012                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6013
6014         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6015         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6016 }
6017
6018 #[test]
6019 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6020         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6021         let chanmon_cfgs = create_chanmon_cfgs(2);
6022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6024         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6025         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6026
6027         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6028         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6029         check_added_monitors!(nodes[0], 1);
6030         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6031         updates.update_add_htlcs[0].amount_msat = 0;
6032
6033         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6034         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6035         check_closed_broadcast!(nodes[1], true).unwrap();
6036         check_added_monitors!(nodes[1], 1);
6037         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6038 }
6039
6040 #[test]
6041 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6042         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6043         //It is enforced when constructing a route.
6044         let chanmon_cfgs = create_chanmon_cfgs(2);
6045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6047         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6048         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6049
6050         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6051                 .with_features(nodes[1].node.invoice_features());
6052         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6053         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6054         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::InvalidRoute { ref err },
6055                 assert_eq!(err, &"Channel CLTV overflowed?"));
6056 }
6057
6058 #[test]
6059 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6060         //BOLT 2 Requirement: if result would be offering more than the remote's max_accepted_htlcs HTLCs, in the remote commitment transaction: MUST NOT add an HTLC.
6061         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6062         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6063         let chanmon_cfgs = create_chanmon_cfgs(2);
6064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6066         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6067         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6068         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6069                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6070
6071         for i in 0..max_accepted_htlcs {
6072                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6073                 let payment_event = {
6074                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6075                         check_added_monitors!(nodes[0], 1);
6076
6077                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6078                         assert_eq!(events.len(), 1);
6079                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6080                                 assert_eq!(htlcs[0].htlc_id, i);
6081                         } else {
6082                                 assert!(false);
6083                         }
6084                         SendEvent::from_event(events.remove(0))
6085                 };
6086                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6087                 check_added_monitors!(nodes[1], 0);
6088                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6089
6090                 expect_pending_htlcs_forwardable!(nodes[1]);
6091                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6092         }
6093         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6094         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6095                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6096
6097         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6098         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6099 }
6100
6101 #[test]
6102 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6103         //BOLT 2 Requirement: if the sum of total offered HTLCs would exceed the remote's max_htlc_value_in_flight_msat: MUST NOT add an HTLC.
6104         let chanmon_cfgs = create_chanmon_cfgs(2);
6105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6107         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6108         let channel_value = 100000;
6109         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6110         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6111
6112         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6113
6114         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6115         // Manually create a route over our max in flight (which our router normally automatically
6116         // limits us to.
6117         route.paths[0][0].fee_msat =  max_in_flight + 1;
6118         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6119                 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6120
6121         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6122         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
6123
6124         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6125 }
6126
6127 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6128 #[test]
6129 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6130         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6131         let chanmon_cfgs = create_chanmon_cfgs(2);
6132         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6134         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6135         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6136         let htlc_minimum_msat: u64;
6137         {
6138                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6139                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6140                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6141                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6142         }
6143
6144         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6145         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6146         check_added_monitors!(nodes[0], 1);
6147         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6148         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6149         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6150         assert!(nodes[1].node.list_channels().is_empty());
6151         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6152         assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6153         check_added_monitors!(nodes[1], 1);
6154         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6155 }
6156
6157 #[test]
6158 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6159         //BOLT2 Requirement: receiving an amount_msat that the sending node cannot afford at the current feerate_per_kw (while maintaining its channel reserve): SHOULD fail the channel
6160         let chanmon_cfgs = create_chanmon_cfgs(2);
6161         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6162         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6163         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6164         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6165
6166         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6167         let channel_reserve = chan_stat.channel_reserve_msat;
6168         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6169         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6170         // The 2* and +1 are for the fee spike reserve.
6171         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6172
6173         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6174         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6175         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6176         check_added_monitors!(nodes[0], 1);
6177         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6178
6179         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6180         // at this time channel-initiatee receivers are not required to enforce that senders
6181         // respect the fee_spike_reserve.
6182         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6183         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6184
6185         assert!(nodes[1].node.list_channels().is_empty());
6186         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6187         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6188         check_added_monitors!(nodes[1], 1);
6189         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6190 }
6191
6192 #[test]
6193 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6194         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6195         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6196         let chanmon_cfgs = create_chanmon_cfgs(2);
6197         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6198         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6199         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6200         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6201
6202         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6203         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6204         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6205         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6206         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6207         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6208
6209         let mut msg = msgs::UpdateAddHTLC {
6210                 channel_id: chan.2,
6211                 htlc_id: 0,
6212                 amount_msat: 1000,
6213                 payment_hash: our_payment_hash,
6214                 cltv_expiry: htlc_cltv,
6215                 onion_routing_packet: onion_packet.clone(),
6216         };
6217
6218         for i in 0..super::channel::OUR_MAX_HTLCS {
6219                 msg.htlc_id = i as u64;
6220                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6221         }
6222         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6223         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6224
6225         assert!(nodes[1].node.list_channels().is_empty());
6226         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6227         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6228         check_added_monitors!(nodes[1], 1);
6229         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6230 }
6231
6232 #[test]
6233 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6234         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6235         let chanmon_cfgs = create_chanmon_cfgs(2);
6236         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6237         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6238         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6239         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6240
6241         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6242         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6243         check_added_monitors!(nodes[0], 1);
6244         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6245         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6246         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6247
6248         assert!(nodes[1].node.list_channels().is_empty());
6249         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6250         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6251         check_added_monitors!(nodes[1], 1);
6252         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6253 }
6254
6255 #[test]
6256 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6257         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6258         let chanmon_cfgs = create_chanmon_cfgs(2);
6259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6261         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6262
6263         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6264         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6265         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6266         check_added_monitors!(nodes[0], 1);
6267         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6268         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6269         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6270
6271         assert!(nodes[1].node.list_channels().is_empty());
6272         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6273         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6274         check_added_monitors!(nodes[1], 1);
6275         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6276 }
6277
6278 #[test]
6279 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6280         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6281         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6282         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6283         let chanmon_cfgs = create_chanmon_cfgs(2);
6284         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6285         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6286         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6287
6288         create_announced_chan_between_nodes(&nodes, 0, 1);
6289         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6290         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6291         check_added_monitors!(nodes[0], 1);
6292         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6293         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6294
6295         //Disconnect and Reconnect
6296         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6297         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6298         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
6299         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6300         assert_eq!(reestablish_1.len(), 1);
6301         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
6302         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6303         assert_eq!(reestablish_2.len(), 1);
6304         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6305         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6306         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6307         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6308
6309         //Resend HTLC
6310         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6311         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6312         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6313         check_added_monitors!(nodes[1], 1);
6314         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6315
6316         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6317
6318         assert!(nodes[1].node.list_channels().is_empty());
6319         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6320         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6321         check_added_monitors!(nodes[1], 1);
6322         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6323 }
6324
6325 #[test]
6326 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6327         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6328
6329         let chanmon_cfgs = create_chanmon_cfgs(2);
6330         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6331         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6332         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6333         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6334         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6335         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6336
6337         check_added_monitors!(nodes[0], 1);
6338         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6339         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6340
6341         let update_msg = msgs::UpdateFulfillHTLC{
6342                 channel_id: chan.2,
6343                 htlc_id: 0,
6344                 payment_preimage: our_payment_preimage,
6345         };
6346
6347         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6348
6349         assert!(nodes[0].node.list_channels().is_empty());
6350         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6351         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6352         check_added_monitors!(nodes[0], 1);
6353         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6354 }
6355
6356 #[test]
6357 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6358         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6359
6360         let chanmon_cfgs = create_chanmon_cfgs(2);
6361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6364         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6365
6366         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6367         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6368         check_added_monitors!(nodes[0], 1);
6369         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6370         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6371
6372         let update_msg = msgs::UpdateFailHTLC{
6373                 channel_id: chan.2,
6374                 htlc_id: 0,
6375                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6376         };
6377
6378         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6379
6380         assert!(nodes[0].node.list_channels().is_empty());
6381         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6382         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6383         check_added_monitors!(nodes[0], 1);
6384         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6385 }
6386
6387 #[test]
6388 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6389         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6390
6391         let chanmon_cfgs = create_chanmon_cfgs(2);
6392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6395         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6396
6397         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6398         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6399         check_added_monitors!(nodes[0], 1);
6400         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6401         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6402         let update_msg = msgs::UpdateFailMalformedHTLC{
6403                 channel_id: chan.2,
6404                 htlc_id: 0,
6405                 sha256_of_onion: [1; 32],
6406                 failure_code: 0x8000,
6407         };
6408
6409         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6410
6411         assert!(nodes[0].node.list_channels().is_empty());
6412         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6413         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6414         check_added_monitors!(nodes[0], 1);
6415         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6416 }
6417
6418 #[test]
6419 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6420         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6421
6422         let chanmon_cfgs = create_chanmon_cfgs(2);
6423         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6424         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6425         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6426         create_announced_chan_between_nodes(&nodes, 0, 1);
6427
6428         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6429
6430         nodes[1].node.claim_funds(our_payment_preimage);
6431         check_added_monitors!(nodes[1], 1);
6432         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6433
6434         let events = nodes[1].node.get_and_clear_pending_msg_events();
6435         assert_eq!(events.len(), 1);
6436         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6437                 match events[0] {
6438                         MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6439                                 assert!(update_add_htlcs.is_empty());
6440                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6441                                 assert!(update_fail_htlcs.is_empty());
6442                                 assert!(update_fail_malformed_htlcs.is_empty());
6443                                 assert!(update_fee.is_none());
6444                                 update_fulfill_htlcs[0].clone()
6445                         },
6446                         _ => panic!("Unexpected event"),
6447                 }
6448         };
6449
6450         update_fulfill_msg.htlc_id = 1;
6451
6452         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6453
6454         assert!(nodes[0].node.list_channels().is_empty());
6455         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6456         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6457         check_added_monitors!(nodes[0], 1);
6458         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6459 }
6460
6461 #[test]
6462 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6463         //BOLT 2 Requirement: A receiving node: if the payment_preimage value in update_fulfill_htlc doesn't SHA256 hash to the corresponding HTLC payment_hash MUST fail the channel.
6464
6465         let chanmon_cfgs = create_chanmon_cfgs(2);
6466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6468         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6469         create_announced_chan_between_nodes(&nodes, 0, 1);
6470
6471         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6472
6473         nodes[1].node.claim_funds(our_payment_preimage);
6474         check_added_monitors!(nodes[1], 1);
6475         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6476
6477         let events = nodes[1].node.get_and_clear_pending_msg_events();
6478         assert_eq!(events.len(), 1);
6479         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6480                 match events[0] {
6481                         MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6482                                 assert!(update_add_htlcs.is_empty());
6483                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6484                                 assert!(update_fail_htlcs.is_empty());
6485                                 assert!(update_fail_malformed_htlcs.is_empty());
6486                                 assert!(update_fee.is_none());
6487                                 update_fulfill_htlcs[0].clone()
6488                         },
6489                         _ => panic!("Unexpected event"),
6490                 }
6491         };
6492
6493         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6494
6495         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6496
6497         assert!(nodes[0].node.list_channels().is_empty());
6498         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6499         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6500         check_added_monitors!(nodes[0], 1);
6501         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6502 }
6503
6504 #[test]
6505 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6506         //BOLT 2 Requirement: A receiving node: if the BADONION bit in failure_code is not set for update_fail_malformed_htlc MUST fail the channel.
6507
6508         let chanmon_cfgs = create_chanmon_cfgs(2);
6509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6511         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6512         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6513
6514         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6515         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6516         check_added_monitors!(nodes[0], 1);
6517
6518         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6519         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6520
6521         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6522         check_added_monitors!(nodes[1], 0);
6523         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6524
6525         let events = nodes[1].node.get_and_clear_pending_msg_events();
6526
6527         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6528                 match events[0] {
6529                         MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6530                                 assert!(update_add_htlcs.is_empty());
6531                                 assert!(update_fulfill_htlcs.is_empty());
6532                                 assert!(update_fail_htlcs.is_empty());
6533                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6534                                 assert!(update_fee.is_none());
6535                                 update_fail_malformed_htlcs[0].clone()
6536                         },
6537                         _ => panic!("Unexpected event"),
6538                 }
6539         };
6540         update_msg.failure_code &= !0x8000;
6541         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6542
6543         assert!(nodes[0].node.list_channels().is_empty());
6544         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6545         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6546         check_added_monitors!(nodes[0], 1);
6547         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6548 }
6549
6550 #[test]
6551 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6552         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6553         //    * MUST return an error in the update_fail_htlc sent to the link which originally sent the HTLC, using the failure_code given and setting the data to sha256_of_onion.
6554
6555         let chanmon_cfgs = create_chanmon_cfgs(3);
6556         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6557         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6558         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6559         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6560         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6561
6562         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6563
6564         //First hop
6565         let mut payment_event = {
6566                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6567                 check_added_monitors!(nodes[0], 1);
6568                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6569                 assert_eq!(events.len(), 1);
6570                 SendEvent::from_event(events.remove(0))
6571         };
6572         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6573         check_added_monitors!(nodes[1], 0);
6574         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6575         expect_pending_htlcs_forwardable!(nodes[1]);
6576         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6577         assert_eq!(events_2.len(), 1);
6578         check_added_monitors!(nodes[1], 1);
6579         payment_event = SendEvent::from_event(events_2.remove(0));
6580         assert_eq!(payment_event.msgs.len(), 1);
6581
6582         //Second Hop
6583         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6584         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6585         check_added_monitors!(nodes[2], 0);
6586         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6587
6588         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6589         assert_eq!(events_3.len(), 1);
6590         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6591                 match events_3[0] {
6592                         MessageSendEvent::UpdateHTLCs { 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 } } => {
6593                                 assert!(update_add_htlcs.is_empty());
6594                                 assert!(update_fulfill_htlcs.is_empty());
6595                                 assert!(update_fail_htlcs.is_empty());
6596                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6597                                 assert!(update_fee.is_none());
6598                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6599                         },
6600                         _ => panic!("Unexpected event"),
6601                 }
6602         };
6603
6604         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6605
6606         check_added_monitors!(nodes[1], 0);
6607         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6608         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6609         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6610         assert_eq!(events_4.len(), 1);
6611
6612         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6613         match events_4[0] {
6614                 MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6615                         assert!(update_add_htlcs.is_empty());
6616                         assert!(update_fulfill_htlcs.is_empty());
6617                         assert_eq!(update_fail_htlcs.len(), 1);
6618                         assert!(update_fail_malformed_htlcs.is_empty());
6619                         assert!(update_fee.is_none());
6620                 },
6621                 _ => panic!("Unexpected event"),
6622         };
6623
6624         check_added_monitors!(nodes[1], 1);
6625 }
6626
6627 #[test]
6628 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6629         let chanmon_cfgs = create_chanmon_cfgs(3);
6630         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6631         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6632         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6633         create_announced_chan_between_nodes(&nodes, 0, 1);
6634         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6635
6636         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6637
6638         // First hop
6639         let mut payment_event = {
6640                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6641                 check_added_monitors!(nodes[0], 1);
6642                 SendEvent::from_node(&nodes[0])
6643         };
6644
6645         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6646         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6647         expect_pending_htlcs_forwardable!(nodes[1]);
6648         check_added_monitors!(nodes[1], 1);
6649         payment_event = SendEvent::from_node(&nodes[1]);
6650         assert_eq!(payment_event.msgs.len(), 1);
6651
6652         // Second Hop
6653         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6654         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6655         check_added_monitors!(nodes[2], 0);
6656         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6657
6658         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6659         assert_eq!(events_3.len(), 1);
6660         match events_3[0] {
6661                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6662                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6663                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6664                         update_msg.failure_code |= 0x2000;
6665
6666                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6667                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6668                 },
6669                 _ => panic!("Unexpected event"),
6670         }
6671
6672         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6673                 vec![HTLCDestination::NextHopChannel {
6674                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6675         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6676         assert_eq!(events_4.len(), 1);
6677         check_added_monitors!(nodes[1], 1);
6678
6679         match events_4[0] {
6680                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6681                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6682                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6683                 },
6684                 _ => panic!("Unexpected event"),
6685         }
6686
6687         let events_5 = nodes[0].node.get_and_clear_pending_events();
6688         assert_eq!(events_5.len(), 2);
6689
6690         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6691         // the node originating the error to its next hop.
6692         match events_5[0] {
6693                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6694                 } => {
6695                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6696                         assert!(is_permanent);
6697                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6698                 },
6699                 _ => panic!("Unexpected event"),
6700         }
6701         match events_5[1] {
6702                 Event::PaymentFailed { payment_hash, .. } => {
6703                         assert_eq!(payment_hash, our_payment_hash);
6704                 },
6705                 _ => panic!("Unexpected event"),
6706         }
6707
6708         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6709 }
6710
6711 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6712         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6713         // We can have at most two valid local commitment tx, so both cases must be covered, and both txs must be checked to get them all as
6714         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6715
6716         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6717         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6721         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6722
6723         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6724                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6725
6726         // We route 2 dust-HTLCs between A and B
6727         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6728         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6729         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6730
6731         // Cache one local commitment tx as previous
6732         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6733
6734         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6735         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6736         check_added_monitors!(nodes[1], 0);
6737         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6738         check_added_monitors!(nodes[1], 1);
6739
6740         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6741         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6742         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6743         check_added_monitors!(nodes[0], 1);
6744
6745         // Cache one local commitment tx as lastest
6746         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6747
6748         let events = nodes[0].node.get_and_clear_pending_msg_events();
6749         match events[0] {
6750                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6751                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6752                 },
6753                 _ => panic!("Unexpected event"),
6754         }
6755         match events[1] {
6756                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6757                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6758                 },
6759                 _ => panic!("Unexpected event"),
6760         }
6761
6762         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6763         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6764         if announce_latest {
6765                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6766         } else {
6767                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6768         }
6769
6770         check_closed_broadcast!(nodes[0], true);
6771         check_added_monitors!(nodes[0], 1);
6772         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6773
6774         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6775         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6776         let events = nodes[0].node.get_and_clear_pending_events();
6777         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6778         assert_eq!(events.len(), 4);
6779         let mut first_failed = false;
6780         for event in events {
6781                 match event {
6782                         Event::PaymentPathFailed { payment_hash, .. } => {
6783                                 if payment_hash == payment_hash_1 {
6784                                         assert!(!first_failed);
6785                                         first_failed = true;
6786                                 } else {
6787                                         assert_eq!(payment_hash, payment_hash_2);
6788                                 }
6789                         },
6790                         Event::PaymentFailed { .. } => {}
6791                         _ => panic!("Unexpected event"),
6792                 }
6793         }
6794 }
6795
6796 #[test]
6797 fn test_failure_delay_dust_htlc_local_commitment() {
6798         do_test_failure_delay_dust_htlc_local_commitment(true);
6799         do_test_failure_delay_dust_htlc_local_commitment(false);
6800 }
6801
6802 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6803         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6804         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6805         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6806         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6807         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6808         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6809
6810         let chanmon_cfgs = create_chanmon_cfgs(3);
6811         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6812         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6813         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6814         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6815
6816         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6817                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6818
6819         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6820         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6821
6822         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6823         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6824
6825         // We revoked bs_commitment_tx
6826         if revoked {
6827                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6828                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6829         }
6830
6831         let mut timeout_tx = Vec::new();
6832         if local {
6833                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6834                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6835                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6836                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6837                 expect_payment_failed!(nodes[0], dust_hash, false);
6838
6839                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6840                 check_closed_broadcast!(nodes[0], true);
6841                 check_added_monitors!(nodes[0], 1);
6842                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6843                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6844                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6845                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6846                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6847                 mine_transaction(&nodes[0], &timeout_tx[0]);
6848                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6849                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6850         } else {
6851                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6852                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6853                 check_closed_broadcast!(nodes[0], true);
6854                 check_added_monitors!(nodes[0], 1);
6855                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6856                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6857
6858                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6859                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6860                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6861                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6862                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6863                 // dust HTLC should have been failed.
6864                 expect_payment_failed!(nodes[0], dust_hash, false);
6865
6866                 if !revoked {
6867                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6868                 } else {
6869                         assert_eq!(timeout_tx[0].lock_time.0, 12);
6870                 }
6871                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6872                 mine_transaction(&nodes[0], &timeout_tx[0]);
6873                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6874                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6875                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6876         }
6877 }
6878
6879 #[test]
6880 fn test_sweep_outbound_htlc_failure_update() {
6881         do_test_sweep_outbound_htlc_failure_update(false, true);
6882         do_test_sweep_outbound_htlc_failure_update(false, false);
6883         do_test_sweep_outbound_htlc_failure_update(true, false);
6884 }
6885
6886 #[test]
6887 fn test_user_configurable_csv_delay() {
6888         // We test our channel constructors yield errors when we pass them absurd csv delay
6889
6890         let mut low_our_to_self_config = UserConfig::default();
6891         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6892         let mut high_their_to_self_config = UserConfig::default();
6893         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6894         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6895         let chanmon_cfgs = create_chanmon_cfgs(2);
6896         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6897         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6898         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6899
6900         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6901         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6902                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6903                 &low_our_to_self_config, 0, 42)
6904         {
6905                 match error {
6906                         APIError::APIMisuseError { err } => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str())); },
6907                         _ => panic!("Unexpected event"),
6908                 }
6909         } else { assert!(false) }
6910
6911         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6912         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6913         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6914         open_channel.to_self_delay = 200;
6915         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6916                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6917                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6918         {
6919                 match error {
6920                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str()));  },
6921                         _ => panic!("Unexpected event"),
6922                 }
6923         } else { assert!(false); }
6924
6925         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6926         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6927         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6928         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6929         accept_channel.to_self_delay = 200;
6930         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6931         let reason_msg;
6932         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6933                 match action {
6934                         &ErrorAction::SendErrorMessage { ref msg } => {
6935                                 assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(msg.data.as_str()));
6936                                 reason_msg = msg.data.clone();
6937                         },
6938                         _ => { panic!(); }
6939                 }
6940         } else { panic!(); }
6941         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6942
6943         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6944         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6945         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6946         open_channel.to_self_delay = 200;
6947         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6948                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6949                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6950         {
6951                 match error {
6952                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(err.as_str())); },
6953                         _ => panic!("Unexpected event"),
6954                 }
6955         } else { assert!(false); }
6956 }
6957
6958 #[test]
6959 fn test_check_htlc_underpaying() {
6960         // Send payment through A -> B but A is maliciously
6961         // sending a probe payment (i.e less than expected value0
6962         // to B, B should refuse payment.
6963
6964         let chanmon_cfgs = create_chanmon_cfgs(2);
6965         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6966         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6967         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6968
6969         // Create some initial channels
6970         create_announced_chan_between_nodes(&nodes, 0, 1);
6971
6972         let scorer = test_utils::TestScorer::new();
6973         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6974         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6975         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
6976         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6977         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6978         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6979         check_added_monitors!(nodes[0], 1);
6980
6981         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6982         assert_eq!(events.len(), 1);
6983         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6984         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6985         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6986
6987         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6988         // and then will wait a second random delay before failing the HTLC back:
6989         expect_pending_htlcs_forwardable!(nodes[1]);
6990         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6991
6992         // Node 3 is expecting payment of 100_000 but received 10_000,
6993         // it should fail htlc like we didn't know the preimage.
6994         nodes[1].node.process_pending_htlc_forwards();
6995
6996         let events = nodes[1].node.get_and_clear_pending_msg_events();
6997         assert_eq!(events.len(), 1);
6998         let (update_fail_htlc, commitment_signed) = match events[0] {
6999                 MessageSendEvent::UpdateHTLCs { 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 } } => {
7000                         assert!(update_add_htlcs.is_empty());
7001                         assert!(update_fulfill_htlcs.is_empty());
7002                         assert_eq!(update_fail_htlcs.len(), 1);
7003                         assert!(update_fail_malformed_htlcs.is_empty());
7004                         assert!(update_fee.is_none());
7005                         (update_fail_htlcs[0].clone(), commitment_signed)
7006                 },
7007                 _ => panic!("Unexpected event"),
7008         };
7009         check_added_monitors!(nodes[1], 1);
7010
7011         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7012         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7013
7014         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7015         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7016         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7017         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7018 }
7019
7020 #[test]
7021 fn test_announce_disable_channels() {
7022         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7023         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7024
7025         let chanmon_cfgs = create_chanmon_cfgs(2);
7026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7028         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7029
7030         create_announced_chan_between_nodes(&nodes, 0, 1);
7031         create_announced_chan_between_nodes(&nodes, 1, 0);
7032         create_announced_chan_between_nodes(&nodes, 0, 1);
7033
7034         // Disconnect peers
7035         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7036         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7037
7038         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7039         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7040         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7041         assert_eq!(msg_events.len(), 3);
7042         let mut chans_disabled = HashMap::new();
7043         for e in msg_events {
7044                 match e {
7045                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7046                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7047                                 // Check that each channel gets updated exactly once
7048                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7049                                         panic!("Generated ChannelUpdate for wrong chan!");
7050                                 }
7051                         },
7052                         _ => panic!("Unexpected event"),
7053                 }
7054         }
7055         // Reconnect peers
7056         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
7057         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7058         assert_eq!(reestablish_1.len(), 3);
7059         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
7060         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7061         assert_eq!(reestablish_2.len(), 3);
7062
7063         // Reestablish chan_1
7064         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7065         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7066         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7067         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7068         // Reestablish chan_2
7069         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7070         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7071         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7072         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7073         // Reestablish chan_3
7074         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7075         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7076         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7077         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7078
7079         nodes[0].node.timer_tick_occurred();
7080         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7081         nodes[0].node.timer_tick_occurred();
7082         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7083         assert_eq!(msg_events.len(), 3);
7084         for e in msg_events {
7085                 match e {
7086                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7087                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7088                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7089                                         // Each update should have a higher timestamp than the previous one, replacing
7090                                         // the old one.
7091                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7092                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7093                                 }
7094                         },
7095                         _ => panic!("Unexpected event"),
7096                 }
7097         }
7098         // Check that each channel gets updated exactly once
7099         assert!(chans_disabled.is_empty());
7100 }
7101
7102 #[test]
7103 fn test_bump_penalty_txn_on_revoked_commitment() {
7104         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7105         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7106
7107         let chanmon_cfgs = create_chanmon_cfgs(2);
7108         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7109         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7110         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7111
7112         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7113
7114         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7115         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7116                 .with_features(nodes[0].node.invoice_features());
7117         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7118         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7119
7120         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7121         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7122         assert_eq!(revoked_txn[0].output.len(), 4);
7123         assert_eq!(revoked_txn[0].input.len(), 1);
7124         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7125         let revoked_txid = revoked_txn[0].txid();
7126
7127         let mut penalty_sum = 0;
7128         for outp in revoked_txn[0].output.iter() {
7129                 if outp.script_pubkey.is_v0_p2wsh() {
7130                         penalty_sum += outp.value;
7131                 }
7132         }
7133
7134         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7135         let header_114 = connect_blocks(&nodes[1], 14);
7136
7137         // Actually revoke tx by claiming a HTLC
7138         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7139         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7140         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7141         check_added_monitors!(nodes[1], 1);
7142
7143         // One or more justice tx should have been broadcast, check it
7144         let penalty_1;
7145         let feerate_1;
7146         {
7147                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7148                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7149                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7150                 assert_eq!(node_txn[0].output.len(), 1);
7151                 check_spends!(node_txn[0], revoked_txn[0]);
7152                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7153                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7154                 penalty_1 = node_txn[0].txid();
7155                 node_txn.clear();
7156         };
7157
7158         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7159         connect_blocks(&nodes[1], 15);
7160         let mut penalty_2 = penalty_1;
7161         let mut feerate_2 = 0;
7162         {
7163                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7164                 assert_eq!(node_txn.len(), 1);
7165                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7166                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7167                         assert_eq!(node_txn[0].output.len(), 1);
7168                         check_spends!(node_txn[0], revoked_txn[0]);
7169                         penalty_2 = node_txn[0].txid();
7170                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7171                         assert_ne!(penalty_2, penalty_1);
7172                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7173                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7174                         // Verify 25% bump heuristic
7175                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7176                         node_txn.clear();
7177                 }
7178         }
7179         assert_ne!(feerate_2, 0);
7180
7181         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7182         connect_blocks(&nodes[1], 1);
7183         let penalty_3;
7184         let mut feerate_3 = 0;
7185         {
7186                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7187                 assert_eq!(node_txn.len(), 1);
7188                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7189                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7190                         assert_eq!(node_txn[0].output.len(), 1);
7191                         check_spends!(node_txn[0], revoked_txn[0]);
7192                         penalty_3 = node_txn[0].txid();
7193                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7194                         assert_ne!(penalty_3, penalty_2);
7195                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7196                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7197                         // Verify 25% bump heuristic
7198                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7199                         node_txn.clear();
7200                 }
7201         }
7202         assert_ne!(feerate_3, 0);
7203
7204         nodes[1].node.get_and_clear_pending_events();
7205         nodes[1].node.get_and_clear_pending_msg_events();
7206 }
7207
7208 #[test]
7209 fn test_bump_penalty_txn_on_revoked_htlcs() {
7210         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7211         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7212
7213         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7214         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7217         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7218
7219         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7220         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7221         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7222         let scorer = test_utils::TestScorer::new();
7223         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7224         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7225                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7226         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7227         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7228         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7229                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7230         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7231
7232         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7233         assert_eq!(revoked_local_txn[0].input.len(), 1);
7234         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7235
7236         // Revoke local commitment tx
7237         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7238
7239         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7240         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7241         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7242         check_closed_broadcast!(nodes[1], true);
7243         check_added_monitors!(nodes[1], 1);
7244         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7245         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7246
7247         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7248         assert_eq!(revoked_htlc_txn.len(), 2);
7249
7250         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7251         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7252         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7253
7254         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7255         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7256         assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7257         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7258
7259         // Broadcast set of revoked txn on A
7260         let hash_128 = connect_blocks(&nodes[0], 40);
7261         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7262         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7263         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7264         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7265         let events = nodes[0].node.get_and_clear_pending_events();
7266         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7267         match events.last().unwrap() {
7268                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7269                 _ => panic!("Unexpected event"),
7270         }
7271         let first;
7272         let feerate_1;
7273         let penalty_txn;
7274         {
7275                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7276                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7277                 // Verify claim tx are spending revoked HTLC txn
7278
7279                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7280                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7281                 // which are included in the same block (they are broadcasted because we scan the
7282                 // transactions linearly and generate claims as we go, they likely should be removed in the
7283                 // future).
7284                 assert_eq!(node_txn[0].input.len(), 1);
7285                 check_spends!(node_txn[0], revoked_local_txn[0]);
7286                 assert_eq!(node_txn[1].input.len(), 1);
7287                 check_spends!(node_txn[1], revoked_local_txn[0]);
7288                 assert_eq!(node_txn[2].input.len(), 1);
7289                 check_spends!(node_txn[2], revoked_local_txn[0]);
7290
7291                 // Each of the three justice transactions claim a separate (single) output of the three
7292                 // available, which we check here:
7293                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7294                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7295                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7296
7297                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7298                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7299
7300                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7301                 // output, checked above).
7302                 assert_eq!(node_txn[3].input.len(), 2);
7303                 assert_eq!(node_txn[3].output.len(), 1);
7304                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7305
7306                 first = node_txn[3].txid();
7307                 // Store both feerates for later comparison
7308                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7309                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7310                 penalty_txn = vec![node_txn[2].clone()];
7311                 node_txn.clear();
7312         }
7313
7314         // Connect one more block to see if bumped penalty are issued for HTLC txn
7315         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7316         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7317         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7318         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7319
7320         // Few more blocks to confirm penalty txn
7321         connect_blocks(&nodes[0], 4);
7322         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7323         let header_144 = connect_blocks(&nodes[0], 9);
7324         let node_txn = {
7325                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7326                 assert_eq!(node_txn.len(), 1);
7327
7328                 assert_eq!(node_txn[0].input.len(), 2);
7329                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7330                 // Verify bumped tx is different and 25% bump heuristic
7331                 assert_ne!(first, node_txn[0].txid());
7332                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7333                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7334                 assert!(feerate_2 * 100 > feerate_1 * 125);
7335                 let txn = vec![node_txn[0].clone()];
7336                 node_txn.clear();
7337                 txn
7338         };
7339         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7340         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7341         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7342         connect_blocks(&nodes[0], 20);
7343         {
7344                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7345                 // We verify than no new transaction has been broadcast because previously
7346                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7347                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7348                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7349                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7350                 // up bumped justice generation.
7351                 assert_eq!(node_txn.len(), 0);
7352                 node_txn.clear();
7353         }
7354         check_closed_broadcast!(nodes[0], true);
7355         check_added_monitors!(nodes[0], 1);
7356 }
7357
7358 #[test]
7359 fn test_bump_penalty_txn_on_remote_commitment() {
7360         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7361         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7362
7363         // Create 2 HTLCs
7364         // Provide preimage for one
7365         // Check aggregation
7366
7367         let chanmon_cfgs = create_chanmon_cfgs(2);
7368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7370         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7371
7372         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7373         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7374         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7375
7376         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7377         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7378         assert_eq!(remote_txn[0].output.len(), 4);
7379         assert_eq!(remote_txn[0].input.len(), 1);
7380         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7381
7382         // Claim a HTLC without revocation (provide B monitor with preimage)
7383         nodes[1].node.claim_funds(payment_preimage);
7384         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7385         mine_transaction(&nodes[1], &remote_txn[0]);
7386         check_added_monitors!(nodes[1], 2);
7387         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7388
7389         // One or more claim tx should have been broadcast, check it
7390         let timeout;
7391         let preimage;
7392         let preimage_bump;
7393         let feerate_timeout;
7394         let feerate_preimage;
7395         {
7396                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7397                 // 3 transactions including:
7398                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7399                 assert_eq!(node_txn.len(), 3);
7400                 assert_eq!(node_txn[0].input.len(), 1);
7401                 assert_eq!(node_txn[1].input.len(), 1);
7402                 assert_eq!(node_txn[2].input.len(), 1);
7403                 check_spends!(node_txn[0], remote_txn[0]);
7404                 check_spends!(node_txn[1], remote_txn[0]);
7405                 check_spends!(node_txn[2], remote_txn[0]);
7406
7407                 preimage = node_txn[0].txid();
7408                 let index = node_txn[0].input[0].previous_output.vout;
7409                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7410                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7411
7412                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7413                         (node_txn[2].clone(), node_txn[1].clone())
7414                 } else {
7415                         (node_txn[1].clone(), node_txn[2].clone())
7416                 };
7417
7418                 preimage_bump = preimage_bump_tx;
7419                 check_spends!(preimage_bump, remote_txn[0]);
7420                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7421
7422                 timeout = timeout_tx.txid();
7423                 let index = timeout_tx.input[0].previous_output.vout;
7424                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7425                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7426
7427                 node_txn.clear();
7428         };
7429         assert_ne!(feerate_timeout, 0);
7430         assert_ne!(feerate_preimage, 0);
7431
7432         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7433         connect_blocks(&nodes[1], 15);
7434         {
7435                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7436                 assert_eq!(node_txn.len(), 1);
7437                 assert_eq!(node_txn[0].input.len(), 1);
7438                 assert_eq!(preimage_bump.input.len(), 1);
7439                 check_spends!(node_txn[0], remote_txn[0]);
7440                 check_spends!(preimage_bump, remote_txn[0]);
7441
7442                 let index = preimage_bump.input[0].previous_output.vout;
7443                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7444                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7445                 assert!(new_feerate * 100 > feerate_timeout * 125);
7446                 assert_ne!(timeout, preimage_bump.txid());
7447
7448                 let index = node_txn[0].input[0].previous_output.vout;
7449                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7450                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7451                 assert!(new_feerate * 100 > feerate_preimage * 125);
7452                 assert_ne!(preimage, node_txn[0].txid());
7453
7454                 node_txn.clear();
7455         }
7456
7457         nodes[1].node.get_and_clear_pending_events();
7458         nodes[1].node.get_and_clear_pending_msg_events();
7459 }
7460
7461 #[test]
7462 fn test_counterparty_raa_skip_no_crash() {
7463         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7464         // commitment transaction, we would have happily carried on and provided them the next
7465         // commitment transaction based on one RAA forward. This would probably eventually have led to
7466         // channel closure, but it would not have resulted in funds loss. Still, our
7467         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7468         // check simply that the channel is closed in response to such an RAA, but don't check whether
7469         // we decide to punish our counterparty for revoking their funds (as we don't currently
7470         // implement that).
7471         let chanmon_cfgs = create_chanmon_cfgs(2);
7472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7475         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7476
7477         let per_commitment_secret;
7478         let next_per_commitment_point;
7479         {
7480                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7481                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7482                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7483
7484                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7485
7486                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7487                 keys.get_enforcement_state().last_holder_commitment -= 1;
7488                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7489
7490                 // Must revoke without gaps
7491                 keys.get_enforcement_state().last_holder_commitment -= 1;
7492                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7493
7494                 keys.get_enforcement_state().last_holder_commitment -= 1;
7495                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7496                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7497         }
7498
7499         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7500                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7501         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7502         check_added_monitors!(nodes[1], 1);
7503         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7504 }
7505
7506 #[test]
7507 fn test_bump_txn_sanitize_tracking_maps() {
7508         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7509         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7510
7511         let chanmon_cfgs = create_chanmon_cfgs(2);
7512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7514         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7515
7516         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7517         // Lock HTLC in both directions
7518         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7519         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7520
7521         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7522         assert_eq!(revoked_local_txn[0].input.len(), 1);
7523         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7524
7525         // Revoke local commitment tx
7526         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7527
7528         // Broadcast set of revoked txn on A
7529         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7530         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7531         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7532
7533         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7534         check_closed_broadcast!(nodes[0], true);
7535         check_added_monitors!(nodes[0], 1);
7536         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7537         let penalty_txn = {
7538                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7539                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7540                 check_spends!(node_txn[0], revoked_local_txn[0]);
7541                 check_spends!(node_txn[1], revoked_local_txn[0]);
7542                 check_spends!(node_txn[2], revoked_local_txn[0]);
7543                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7544                 node_txn.clear();
7545                 penalty_txn
7546         };
7547         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7548         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7549         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7550         {
7551                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7552                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7553                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7554         }
7555 }
7556
7557 #[test]
7558 fn test_pending_claimed_htlc_no_balance_underflow() {
7559         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7560         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7561         let chanmon_cfgs = create_chanmon_cfgs(2);
7562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7564         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7565         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7566
7567         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7568         nodes[1].node.claim_funds(payment_preimage);
7569         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7570         check_added_monitors!(nodes[1], 1);
7571         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7572
7573         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7574         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7575         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7576         check_added_monitors!(nodes[0], 1);
7577         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7578
7579         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7580         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7581         // can get our balance.
7582
7583         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7584         // the public key of the only hop. This works around ChannelDetails not showing the
7585         // almost-claimed HTLC as available balance.
7586         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7587         route.payment_params = None; // This is all wrong, but unnecessary
7588         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7589         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7590         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7591
7592         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7593 }
7594
7595 #[test]
7596 fn test_channel_conf_timeout() {
7597         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7598         // confirm within 2016 blocks, as recommended by BOLT 2.
7599         let chanmon_cfgs = create_chanmon_cfgs(2);
7600         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7602         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7603
7604         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7605
7606         // The outbound node should wait forever for confirmation:
7607         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7608         // copied here instead of directly referencing the constant.
7609         connect_blocks(&nodes[0], 2016);
7610         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7611
7612         // The inbound node should fail the channel after exactly 2016 blocks
7613         connect_blocks(&nodes[1], 2015);
7614         check_added_monitors!(nodes[1], 0);
7615         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7616
7617         connect_blocks(&nodes[1], 1);
7618         check_added_monitors!(nodes[1], 1);
7619         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7620         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7621         assert_eq!(close_ev.len(), 1);
7622         match close_ev[0] {
7623                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7624                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7625                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7626                 },
7627                 _ => panic!("Unexpected event"),
7628         }
7629 }
7630
7631 #[test]
7632 fn test_override_channel_config() {
7633         let chanmon_cfgs = create_chanmon_cfgs(2);
7634         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7635         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7636         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7637
7638         // Node0 initiates a channel to node1 using the override config.
7639         let mut override_config = UserConfig::default();
7640         override_config.channel_handshake_config.our_to_self_delay = 200;
7641
7642         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7643
7644         // Assert the channel created by node0 is using the override config.
7645         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7646         assert_eq!(res.channel_flags, 0);
7647         assert_eq!(res.to_self_delay, 200);
7648 }
7649
7650 #[test]
7651 fn test_override_0msat_htlc_minimum() {
7652         let mut zero_config = UserConfig::default();
7653         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7654         let chanmon_cfgs = create_chanmon_cfgs(2);
7655         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7656         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7657         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7658
7659         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7660         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7661         assert_eq!(res.htlc_minimum_msat, 1);
7662
7663         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7664         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7665         assert_eq!(res.htlc_minimum_msat, 1);
7666 }
7667
7668 #[test]
7669 fn test_channel_update_has_correct_htlc_maximum_msat() {
7670         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7671         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7672         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7673         // 90% of the `channel_value`.
7674         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7675
7676         let mut config_30_percent = UserConfig::default();
7677         config_30_percent.channel_handshake_config.announced_channel = true;
7678         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7679         let mut config_50_percent = UserConfig::default();
7680         config_50_percent.channel_handshake_config.announced_channel = true;
7681         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7682         let mut config_95_percent = UserConfig::default();
7683         config_95_percent.channel_handshake_config.announced_channel = true;
7684         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7685         let mut config_100_percent = UserConfig::default();
7686         config_100_percent.channel_handshake_config.announced_channel = true;
7687         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7688
7689         let chanmon_cfgs = create_chanmon_cfgs(4);
7690         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7691         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[Some(config_30_percent), Some(config_50_percent), Some(config_95_percent), Some(config_100_percent)]);
7692         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7693
7694         let channel_value_satoshis = 100000;
7695         let channel_value_msat = channel_value_satoshis * 1000;
7696         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7697         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7698         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7699
7700         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7701         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7702
7703         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7704         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7705         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7706         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7707         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7708         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7709
7710         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7711         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7712         // `channel_value`.
7713         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7714         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7715         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7716         // `channel_value`.
7717         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7718 }
7719
7720 #[test]
7721 fn test_manually_accept_inbound_channel_request() {
7722         let mut manually_accept_conf = UserConfig::default();
7723         manually_accept_conf.manually_accept_inbound_channels = true;
7724         let chanmon_cfgs = create_chanmon_cfgs(2);
7725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7727         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7728
7729         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7730         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7731
7732         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7733
7734         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7735         // accepting the inbound channel request.
7736         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7737
7738         let events = nodes[1].node.get_and_clear_pending_events();
7739         match events[0] {
7740                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7741                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7742                 }
7743                 _ => panic!("Unexpected event"),
7744         }
7745
7746         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7747         assert_eq!(accept_msg_ev.len(), 1);
7748
7749         match accept_msg_ev[0] {
7750                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7751                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7752                 }
7753                 _ => panic!("Unexpected event"),
7754         }
7755
7756         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7757
7758         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7759         assert_eq!(close_msg_ev.len(), 1);
7760
7761         let events = nodes[1].node.get_and_clear_pending_events();
7762         match events[0] {
7763                 Event::ChannelClosed { user_channel_id, .. } => {
7764                         assert_eq!(user_channel_id, 23);
7765                 }
7766                 _ => panic!("Unexpected event"),
7767         }
7768 }
7769
7770 #[test]
7771 fn test_manually_reject_inbound_channel_request() {
7772         let mut manually_accept_conf = UserConfig::default();
7773         manually_accept_conf.manually_accept_inbound_channels = true;
7774         let chanmon_cfgs = create_chanmon_cfgs(2);
7775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7777         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7778
7779         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7780         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7781
7782         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7783
7784         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7785         // rejecting the inbound channel request.
7786         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7787
7788         let events = nodes[1].node.get_and_clear_pending_events();
7789         match events[0] {
7790                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7791                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7792                 }
7793                 _ => panic!("Unexpected event"),
7794         }
7795
7796         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7797         assert_eq!(close_msg_ev.len(), 1);
7798
7799         match close_msg_ev[0] {
7800                 MessageSendEvent::HandleError { ref node_id, .. } => {
7801                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7802                 }
7803                 _ => panic!("Unexpected event"),
7804         }
7805         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7806 }
7807
7808 #[test]
7809 fn test_reject_funding_before_inbound_channel_accepted() {
7810         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7811         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7812         // the node operator before the counterparty sends a `FundingCreated` message. If a
7813         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7814         // and the channel should be closed.
7815         let mut manually_accept_conf = UserConfig::default();
7816         manually_accept_conf.manually_accept_inbound_channels = true;
7817         let chanmon_cfgs = create_chanmon_cfgs(2);
7818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7820         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7821
7822         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7823         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7824         let temp_channel_id = res.temporary_channel_id;
7825
7826         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7827
7828         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7829         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7830
7831         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7832         nodes[1].node.get_and_clear_pending_events();
7833
7834         // Get the `AcceptChannel` message of `nodes[1]` without calling
7835         // `ChannelManager::accept_inbound_channel`, which generates a
7836         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7837         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7838         // succeed when `nodes[0]` is passed to it.
7839         let accept_chan_msg = {
7840                 let mut node_1_per_peer_lock;
7841                 let mut node_1_peer_state_lock;
7842                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7843                 channel.get_accept_channel_message()
7844         };
7845         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7846
7847         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7848
7849         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7850         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7851
7852         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7853         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7854
7855         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7856         assert_eq!(close_msg_ev.len(), 1);
7857
7858         let expected_err = "FundingCreated message received before the channel was accepted";
7859         match close_msg_ev[0] {
7860                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7861                         assert_eq!(msg.channel_id, temp_channel_id);
7862                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7863                         assert_eq!(msg.data, expected_err);
7864                 }
7865                 _ => panic!("Unexpected event"),
7866         }
7867
7868         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7869 }
7870
7871 #[test]
7872 fn test_can_not_accept_inbound_channel_twice() {
7873         let mut manually_accept_conf = UserConfig::default();
7874         manually_accept_conf.manually_accept_inbound_channels = true;
7875         let chanmon_cfgs = create_chanmon_cfgs(2);
7876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7878         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7879
7880         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7881         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7882
7883         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7884
7885         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7886         // accepting the inbound channel request.
7887         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7888
7889         let events = nodes[1].node.get_and_clear_pending_events();
7890         match events[0] {
7891                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7892                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7893                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7894                         match api_res {
7895                                 Err(APIError::APIMisuseError { err }) => {
7896                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7897                                 },
7898                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7899                                 Err(_) => panic!("Unexpected Error"),
7900                         }
7901                 }
7902                 _ => panic!("Unexpected event"),
7903         }
7904
7905         // Ensure that the channel wasn't closed after attempting to accept it twice.
7906         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7907         assert_eq!(accept_msg_ev.len(), 1);
7908
7909         match accept_msg_ev[0] {
7910                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7911                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7912                 }
7913                 _ => panic!("Unexpected event"),
7914         }
7915 }
7916
7917 #[test]
7918 fn test_can_not_accept_unknown_inbound_channel() {
7919         let chanmon_cfg = create_chanmon_cfgs(2);
7920         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7921         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7922         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7923
7924         let unknown_channel_id = [0; 32];
7925         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7926         match api_res {
7927                 Err(APIError::ChannelUnavailable { err }) => {
7928                         assert_eq!(err, format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(unknown_channel_id), nodes[1].node.get_our_node_id()));
7929                 },
7930                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7931                 Err(_) => panic!("Unexpected Error"),
7932         }
7933 }
7934
7935 #[test]
7936 fn test_onion_value_mpp_set_calculation() {
7937         // Test that we use the onion value `amt_to_forward` when
7938         // calculating whether we've reached the `total_msat` of an MPP
7939         // by having a routing node forward more than `amt_to_forward`
7940         // and checking that the receiving node doesn't generate
7941         // a PaymentClaimable event too early
7942         let node_count = 4;
7943         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7944         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7945         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7946         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7947
7948         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7949         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7950         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7951         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7952
7953         let total_msat = 100_000;
7954         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7955         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7956         let sample_path = route.paths.pop().unwrap();
7957
7958         let mut path_1 = sample_path.clone();
7959         path_1[0].pubkey = nodes[1].node.get_our_node_id();
7960         path_1[0].short_channel_id = chan_1_id;
7961         path_1[1].pubkey = nodes[3].node.get_our_node_id();
7962         path_1[1].short_channel_id = chan_3_id;
7963         path_1[1].fee_msat = 100_000;
7964         route.paths.push(path_1);
7965
7966         let mut path_2 = sample_path.clone();
7967         path_2[0].pubkey = nodes[2].node.get_our_node_id();
7968         path_2[0].short_channel_id = chan_2_id;
7969         path_2[1].pubkey = nodes[3].node.get_our_node_id();
7970         path_2[1].short_channel_id = chan_4_id;
7971         path_2[1].fee_msat = 1_000;
7972         route.paths.push(path_2);
7973
7974         // Send payment
7975         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7976         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
7977         nodes[0].node.test_send_payment_internal(&route, our_payment_hash, &Some(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
7978         check_added_monitors!(nodes[0], expected_paths.len());
7979
7980         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7981         assert_eq!(events.len(), expected_paths.len());
7982
7983         // First path
7984         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
7985         let mut payment_event = SendEvent::from_event(ev);
7986         let mut prev_node = &nodes[0];
7987
7988         for (idx, &node) in expected_paths[0].iter().enumerate() {
7989                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
7990
7991                 if idx == 0 { // routing node
7992                         let session_priv = [3; 32];
7993                         let height = nodes[0].best_block_info().1;
7994                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
7995                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
7996                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000, &Some(our_payment_secret), height + 1, &None).unwrap();
7997                         // Edit amt_to_forward to simulate the sender having set
7998                         // the final amount and the routing node taking less fee
7999                         onion_payloads[1].amt_to_forward = 99_000;
8000                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8001                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8002                 }
8003
8004                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8005                 check_added_monitors!(node, 0);
8006                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8007                 expect_pending_htlcs_forwardable!(node);
8008
8009                 if idx == 0 {
8010                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8011                         assert_eq!(events_2.len(), 1);
8012                         check_added_monitors!(node, 1);
8013                         payment_event = SendEvent::from_event(events_2.remove(0));
8014                         assert_eq!(payment_event.msgs.len(), 1);
8015                 } else {
8016                         let events_2 = node.node.get_and_clear_pending_events();
8017                         assert!(events_2.is_empty());
8018                 }
8019
8020                 prev_node = node;
8021         }
8022
8023         // Second path
8024         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8025         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8026
8027         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8028 }
8029
8030 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8031
8032         let routing_node_count = msat_amounts.len();
8033         let node_count = routing_node_count + 2;
8034
8035         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8036         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8037         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8038         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8039
8040         let src_idx = 0;
8041         let dst_idx = 1;
8042
8043         // Create channels for each amount
8044         let mut expected_paths = Vec::with_capacity(routing_node_count);
8045         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8046         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8047         for i in 0..routing_node_count {
8048                 let routing_node = 2 + i;
8049                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8050                 src_chan_ids.push(src_chan_id);
8051                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8052                 dst_chan_ids.push(dst_chan_id);
8053                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8054                 expected_paths.push(path);
8055         }
8056         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8057
8058         // Create a route for each amount
8059         let example_amount = 100000;
8060         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[src_idx], nodes[dst_idx], example_amount);
8061         let sample_path = route.paths.pop().unwrap();
8062         for i in 0..routing_node_count {
8063                 let routing_node = 2 + i;
8064                 let mut path = sample_path.clone();
8065                 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8066                 path[0].short_channel_id = src_chan_ids[i];
8067                 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8068                 path[1].short_channel_id = dst_chan_ids[i];
8069                 path[1].fee_msat = msat_amounts[i];
8070                 route.paths.push(path);
8071         }
8072
8073         // Send payment with manually set total_msat
8074         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8075         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
8076         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash, &Some(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8077         check_added_monitors!(nodes[src_idx], expected_paths.len());
8078
8079         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8080         assert_eq!(events.len(), expected_paths.len());
8081         let mut amount_received = 0;
8082         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8083                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8084
8085                 let current_path_amount = msat_amounts[path_idx];
8086                 amount_received += current_path_amount;
8087                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8088                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8089         }
8090
8091         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8092 }
8093
8094 #[test]
8095 fn test_overshoot_mpp() {
8096         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8097         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8098 }
8099
8100 #[test]
8101 fn test_simple_mpp() {
8102         // Simple test of sending a multi-path payment.
8103         let chanmon_cfgs = create_chanmon_cfgs(4);
8104         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8105         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8106         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8107
8108         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8109         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8110         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8111         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8112
8113         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8114         let path = route.paths[0].clone();
8115         route.paths.push(path);
8116         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8117         route.paths[0][0].short_channel_id = chan_1_id;
8118         route.paths[0][1].short_channel_id = chan_3_id;
8119         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8120         route.paths[1][0].short_channel_id = chan_2_id;
8121         route.paths[1][1].short_channel_id = chan_4_id;
8122         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8123         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8124 }
8125
8126 #[test]
8127 fn test_preimage_storage() {
8128         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8129         let chanmon_cfgs = create_chanmon_cfgs(2);
8130         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8132         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8133
8134         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8135
8136         {
8137                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8138                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8139                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8140                 check_added_monitors!(nodes[0], 1);
8141                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8142                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8143                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8144                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8145         }
8146         // Note that after leaving the above scope we have no knowledge of any arguments or return
8147         // values from previous calls.
8148         expect_pending_htlcs_forwardable!(nodes[1]);
8149         let events = nodes[1].node.get_and_clear_pending_events();
8150         assert_eq!(events.len(), 1);
8151         match events[0] {
8152                 Event::PaymentClaimable { ref purpose, .. } => {
8153                         match &purpose {
8154                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8155                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8156                                 },
8157                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8158                         }
8159                 },
8160                 _ => panic!("Unexpected event"),
8161         }
8162 }
8163
8164 #[test]
8165 #[allow(deprecated)]
8166 fn test_secret_timeout() {
8167         // Simple test of payment secret storage time outs. After
8168         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8169         let chanmon_cfgs = create_chanmon_cfgs(2);
8170         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8172         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8173
8174         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8175
8176         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8177
8178         // We should fail to register the same payment hash twice, at least until we've connected a
8179         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8180         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8181                 assert_eq!(err, "Duplicate payment hash");
8182         } else { panic!(); }
8183         let mut block = {
8184                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8185                 Block {
8186                         header: BlockHeader {
8187                                 version: 0x2000000,
8188                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8189                                 merkle_root: TxMerkleNode::all_zeros(),
8190                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8191                         txdata: vec![],
8192                 }
8193         };
8194         connect_block(&nodes[1], &block);
8195         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8196                 assert_eq!(err, "Duplicate payment hash");
8197         } else { panic!(); }
8198
8199         // If we then connect the second block, we should be able to register the same payment hash
8200         // again (this time getting a new payment secret).
8201         block.header.prev_blockhash = block.header.block_hash();
8202         block.header.time += 1;
8203         connect_block(&nodes[1], &block);
8204         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8205         assert_ne!(payment_secret_1, our_payment_secret);
8206
8207         {
8208                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8209                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8210                 check_added_monitors!(nodes[0], 1);
8211                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8212                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8213                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8214                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8215         }
8216         // Note that after leaving the above scope we have no knowledge of any arguments or return
8217         // values from previous calls.
8218         expect_pending_htlcs_forwardable!(nodes[1]);
8219         let events = nodes[1].node.get_and_clear_pending_events();
8220         assert_eq!(events.len(), 1);
8221         match events[0] {
8222                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8223                         assert!(payment_preimage.is_none());
8224                         assert_eq!(payment_secret, our_payment_secret);
8225                         // We don't actually have the payment preimage with which to claim this payment!
8226                 },
8227                 _ => panic!("Unexpected event"),
8228         }
8229 }
8230
8231 #[test]
8232 fn test_bad_secret_hash() {
8233         // Simple test of unregistered payment hash/invalid payment secret handling
8234         let chanmon_cfgs = create_chanmon_cfgs(2);
8235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8237         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8238
8239         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8240
8241         let random_payment_hash = PaymentHash([42; 32]);
8242         let random_payment_secret = PaymentSecret([43; 32]);
8243         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8244         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8245
8246         // All the below cases should end up being handled exactly identically, so we macro the
8247         // resulting events.
8248         macro_rules! handle_unknown_invalid_payment_data {
8249                 ($payment_hash: expr) => {
8250                         check_added_monitors!(nodes[0], 1);
8251                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8252                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8253                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8254                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8255
8256                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8257                         // again to process the pending backwards-failure of the HTLC
8258                         expect_pending_htlcs_forwardable!(nodes[1]);
8259                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8260                         check_added_monitors!(nodes[1], 1);
8261
8262                         // We should fail the payment back
8263                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8264                         match events.pop().unwrap() {
8265                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8266                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8267                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8268                                 },
8269                                 _ => panic!("Unexpected event"),
8270                         }
8271                 }
8272         }
8273
8274         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8275         // Error data is the HTLC value (100,000) and current block height
8276         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8277
8278         // Send a payment with the right payment hash but the wrong payment secret
8279         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8280         handle_unknown_invalid_payment_data!(our_payment_hash);
8281         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8282
8283         // Send a payment with a random payment hash, but the right payment secret
8284         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8285         handle_unknown_invalid_payment_data!(random_payment_hash);
8286         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8287
8288         // Send a payment with a random payment hash and random payment secret
8289         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8290         handle_unknown_invalid_payment_data!(random_payment_hash);
8291         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8292 }
8293
8294 #[test]
8295 fn test_update_err_monitor_lockdown() {
8296         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8297         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8298         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8299         // error.
8300         //
8301         // This scenario may happen in a watchtower setup, where watchtower process a block height
8302         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8303         // commitment at same time.
8304
8305         let chanmon_cfgs = create_chanmon_cfgs(2);
8306         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8307         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8308         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8309
8310         // Create some initial channel
8311         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8312         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8313
8314         // Rebalance the network to generate htlc in the two directions
8315         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8316
8317         // Route a HTLC from node 0 to node 1 (but don't settle)
8318         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8319
8320         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8321         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8322         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8323         let persister = test_utils::TestPersister::new();
8324         let watchtower = {
8325                 let new_monitor = {
8326                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8327                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8328                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8329                         assert!(new_monitor == *monitor);
8330                         new_monitor
8331                 };
8332                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8333                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8334                 watchtower
8335         };
8336         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8337         let block = Block { header, txdata: vec![] };
8338         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8339         // transaction lock time requirements here.
8340         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8341         watchtower.chain_monitor.block_connected(&block, 200);
8342
8343         // Try to update ChannelMonitor
8344         nodes[1].node.claim_funds(preimage);
8345         check_added_monitors!(nodes[1], 1);
8346         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8347
8348         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8349         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8350         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8351         {
8352                 let mut node_0_per_peer_lock;
8353                 let mut node_0_peer_state_lock;
8354                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8355                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8356                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8357                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8358                 } else { assert!(false); }
8359         }
8360         // Our local monitor is in-sync and hasn't processed yet timeout
8361         check_added_monitors!(nodes[0], 1);
8362         let events = nodes[0].node.get_and_clear_pending_events();
8363         assert_eq!(events.len(), 1);
8364 }
8365
8366 #[test]
8367 fn test_concurrent_monitor_claim() {
8368         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8369         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8370         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8371         // state N+1 confirms. Alice claims output from state N+1.
8372
8373         let chanmon_cfgs = create_chanmon_cfgs(2);
8374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8376         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8377
8378         // Create some initial channel
8379         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8380         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8381
8382         // Rebalance the network to generate htlc in the two directions
8383         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8384
8385         // Route a HTLC from node 0 to node 1 (but don't settle)
8386         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8387
8388         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8389         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8390         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8391         let persister = test_utils::TestPersister::new();
8392         let watchtower_alice = {
8393                 let new_monitor = {
8394                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8395                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8396                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8397                         assert!(new_monitor == *monitor);
8398                         new_monitor
8399                 };
8400                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8401                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8402                 watchtower
8403         };
8404         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8405         let block = Block { header, txdata: vec![] };
8406         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8407         // transaction lock time requirements here.
8408         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8409         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8410
8411         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8412         {
8413                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8414                 assert_eq!(txn.len(), 2);
8415                 txn.clear();
8416         }
8417
8418         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8419         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8420         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8421         let persister = test_utils::TestPersister::new();
8422         let watchtower_bob = {
8423                 let new_monitor = {
8424                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8425                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8426                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8427                         assert!(new_monitor == *monitor);
8428                         new_monitor
8429                 };
8430                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8431                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8432                 watchtower
8433         };
8434         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8435         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8436
8437         // Route another payment to generate another update with still previous HTLC pending
8438         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8439         {
8440                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8441         }
8442         check_added_monitors!(nodes[1], 1);
8443
8444         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8445         assert_eq!(updates.update_add_htlcs.len(), 1);
8446         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8447         {
8448                 let mut node_0_per_peer_lock;
8449                 let mut node_0_peer_state_lock;
8450                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8451                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8452                         // Watchtower Alice should already have seen the block and reject the update
8453                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8454                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8455                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8456                 } else { assert!(false); }
8457         }
8458         // Our local monitor is in-sync and hasn't processed yet timeout
8459         check_added_monitors!(nodes[0], 1);
8460
8461         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8462         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8463         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8464
8465         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8466         let bob_state_y;
8467         {
8468                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8469                 assert_eq!(txn.len(), 2);
8470                 bob_state_y = txn[0].clone();
8471                 txn.clear();
8472         };
8473
8474         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8475         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8476         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8477         {
8478                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8479                 assert_eq!(htlc_txn.len(), 1);
8480                 check_spends!(htlc_txn[0], bob_state_y);
8481         }
8482 }
8483
8484 #[test]
8485 fn test_pre_lockin_no_chan_closed_update() {
8486         // Test that if a peer closes a channel in response to a funding_created message we don't
8487         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8488         // message).
8489         //
8490         // Doing so would imply a channel monitor update before the initial channel monitor
8491         // registration, violating our API guarantees.
8492         //
8493         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8494         // then opening a second channel with the same funding output as the first (which is not
8495         // rejected because the first channel does not exist in the ChannelManager) and closing it
8496         // before receiving funding_signed.
8497         let chanmon_cfgs = create_chanmon_cfgs(2);
8498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8501
8502         // Create an initial channel
8503         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8504         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8505         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8506         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8507         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8508
8509         // Move the first channel through the funding flow...
8510         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8511
8512         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8513         check_added_monitors!(nodes[0], 0);
8514
8515         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8516         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8517         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8518         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8519         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8520 }
8521
8522 #[test]
8523 fn test_htlc_no_detection() {
8524         // This test is a mutation to underscore the detection logic bug we had
8525         // before #653. HTLC value routed is above the remaining balance, thus
8526         // inverting HTLC and `to_remote` output. HTLC will come second and
8527         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8528         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8529         // outputs order detection for correct spending children filtring.
8530
8531         let chanmon_cfgs = create_chanmon_cfgs(2);
8532         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8533         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8534         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8535
8536         // Create some initial channels
8537         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8538
8539         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8540         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8541         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8542         assert_eq!(local_txn[0].input.len(), 1);
8543         assert_eq!(local_txn[0].output.len(), 3);
8544         check_spends!(local_txn[0], chan_1.3);
8545
8546         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8547         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8548         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8549         // We deliberately connect the local tx twice as this should provoke a failure calling
8550         // this test before #653 fix.
8551         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8552         check_closed_broadcast!(nodes[0], true);
8553         check_added_monitors!(nodes[0], 1);
8554         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8555         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8556
8557         let htlc_timeout = {
8558                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8559                 assert_eq!(node_txn.len(), 1);
8560                 assert_eq!(node_txn[0].input.len(), 1);
8561                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8562                 check_spends!(node_txn[0], local_txn[0]);
8563                 node_txn[0].clone()
8564         };
8565
8566         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8567         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8568         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8569         expect_payment_failed!(nodes[0], our_payment_hash, false);
8570 }
8571
8572 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8573         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8574         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8575         // Carol, Alice would be the upstream node, and Carol the downstream.)
8576         //
8577         // Steps of the test:
8578         // 1) Alice sends a HTLC to Carol through Bob.
8579         // 2) Carol doesn't settle the HTLC.
8580         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8581         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8582         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8583         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8584         // 5) Carol release the preimage to Bob off-chain.
8585         // 6) Bob claims the offered output on the broadcasted commitment.
8586         let chanmon_cfgs = create_chanmon_cfgs(3);
8587         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8588         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8589         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8590
8591         // Create some initial channels
8592         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8593         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8594
8595         // Steps (1) and (2):
8596         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8597         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8598
8599         // Check that Alice's commitment transaction now contains an output for this HTLC.
8600         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8601         check_spends!(alice_txn[0], chan_ab.3);
8602         assert_eq!(alice_txn[0].output.len(), 2);
8603         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8604         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8605         assert_eq!(alice_txn.len(), 2);
8606
8607         // Steps (3) and (4):
8608         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8609         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8610         let mut force_closing_node = 0; // Alice force-closes
8611         let mut counterparty_node = 1; // Bob if Alice force-closes
8612
8613         // Bob force-closes
8614         if !broadcast_alice {
8615                 force_closing_node = 1;
8616                 counterparty_node = 0;
8617         }
8618         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8619         check_closed_broadcast!(nodes[force_closing_node], true);
8620         check_added_monitors!(nodes[force_closing_node], 1);
8621         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8622         if go_onchain_before_fulfill {
8623                 let txn_to_broadcast = match broadcast_alice {
8624                         true => alice_txn.clone(),
8625                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8626                 };
8627                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8628                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8629                 if broadcast_alice {
8630                         check_closed_broadcast!(nodes[1], true);
8631                         check_added_monitors!(nodes[1], 1);
8632                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8633                 }
8634         }
8635
8636         // Step (5):
8637         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8638         // process of removing the HTLC from their commitment transactions.
8639         nodes[2].node.claim_funds(payment_preimage);
8640         check_added_monitors!(nodes[2], 1);
8641         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8642
8643         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8644         assert!(carol_updates.update_add_htlcs.is_empty());
8645         assert!(carol_updates.update_fail_htlcs.is_empty());
8646         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8647         assert!(carol_updates.update_fee.is_none());
8648         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8649
8650         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8651         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8652         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8653         if !go_onchain_before_fulfill && broadcast_alice {
8654                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8655                 assert_eq!(events.len(), 1);
8656                 match events[0] {
8657                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8658                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8659                         },
8660                         _ => panic!("Unexpected event"),
8661                 };
8662         }
8663         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8664         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8665         // Carol<->Bob's updated commitment transaction info.
8666         check_added_monitors!(nodes[1], 2);
8667
8668         let events = nodes[1].node.get_and_clear_pending_msg_events();
8669         assert_eq!(events.len(), 2);
8670         let bob_revocation = match events[0] {
8671                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8672                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8673                         (*msg).clone()
8674                 },
8675                 _ => panic!("Unexpected event"),
8676         };
8677         let bob_updates = match events[1] {
8678                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8679                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8680                         (*updates).clone()
8681                 },
8682                 _ => panic!("Unexpected event"),
8683         };
8684
8685         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8686         check_added_monitors!(nodes[2], 1);
8687         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8688         check_added_monitors!(nodes[2], 1);
8689
8690         let events = nodes[2].node.get_and_clear_pending_msg_events();
8691         assert_eq!(events.len(), 1);
8692         let carol_revocation = match events[0] {
8693                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8694                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8695                         (*msg).clone()
8696                 },
8697                 _ => panic!("Unexpected event"),
8698         };
8699         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8700         check_added_monitors!(nodes[1], 1);
8701
8702         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8703         // here's where we put said channel's commitment tx on-chain.
8704         let mut txn_to_broadcast = alice_txn.clone();
8705         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8706         if !go_onchain_before_fulfill {
8707                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8708                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8709                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8710                 if broadcast_alice {
8711                         check_closed_broadcast!(nodes[1], true);
8712                         check_added_monitors!(nodes[1], 1);
8713                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8714                 }
8715                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8716                 if broadcast_alice {
8717                         assert_eq!(bob_txn.len(), 1);
8718                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8719                 } else {
8720                         assert_eq!(bob_txn.len(), 2);
8721                         check_spends!(bob_txn[0], chan_ab.3);
8722                 }
8723         }
8724
8725         // Step (6):
8726         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8727         // broadcasted commitment transaction.
8728         {
8729                 let script_weight = match broadcast_alice {
8730                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8731                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8732                 };
8733                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8734                 // Bob force-closed and broadcasts the commitment transaction along with a
8735                 // HTLC-output-claiming transaction.
8736                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8737                 if broadcast_alice {
8738                         assert_eq!(bob_txn.len(), 1);
8739                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8740                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8741                 } else {
8742                         assert_eq!(bob_txn.len(), 2);
8743                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8744                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8745                 }
8746         }
8747 }
8748
8749 #[test]
8750 fn test_onchain_htlc_settlement_after_close() {
8751         do_test_onchain_htlc_settlement_after_close(true, true);
8752         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8753         do_test_onchain_htlc_settlement_after_close(true, false);
8754         do_test_onchain_htlc_settlement_after_close(false, false);
8755 }
8756
8757 #[test]
8758 fn test_duplicate_temporary_channel_id_from_different_peers() {
8759         // Tests that we can accept two different `OpenChannel` requests with the same
8760         // `temporary_channel_id`, as long as they are from different peers.
8761         let chanmon_cfgs = create_chanmon_cfgs(3);
8762         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8763         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8764         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8765
8766         // Create an first channel channel
8767         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8768         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8769
8770         // Create an second channel
8771         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8772         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8773
8774         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8775         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8776         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8777
8778         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8779         // `temporary_channel_id` as they are from different peers.
8780         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8781         {
8782                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8783                 assert_eq!(events.len(), 1);
8784                 match &events[0] {
8785                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8786                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8787                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8788                         },
8789                         _ => panic!("Unexpected event"),
8790                 }
8791         }
8792
8793         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8794         {
8795                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8796                 assert_eq!(events.len(), 1);
8797                 match &events[0] {
8798                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8799                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8800                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8801                         },
8802                         _ => panic!("Unexpected event"),
8803                 }
8804         }
8805 }
8806
8807 #[test]
8808 fn test_duplicate_chan_id() {
8809         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8810         // already open we reject it and keep the old channel.
8811         //
8812         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8813         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8814         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8815         // updating logic for the existing channel.
8816         let chanmon_cfgs = create_chanmon_cfgs(2);
8817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8820
8821         // Create an initial channel
8822         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8823         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8824         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8825         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8826
8827         // Try to create a second channel with the same temporary_channel_id as the first and check
8828         // that it is rejected.
8829         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8830         {
8831                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8832                 assert_eq!(events.len(), 1);
8833                 match events[0] {
8834                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8835                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8836                                 // first (valid) and second (invalid) channels are closed, given they both have
8837                                 // the same non-temporary channel_id. However, currently we do not, so we just
8838                                 // move forward with it.
8839                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8840                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8841                         },
8842                         _ => panic!("Unexpected event"),
8843                 }
8844         }
8845
8846         // Move the first channel through the funding flow...
8847         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8848
8849         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8850         check_added_monitors!(nodes[0], 0);
8851
8852         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8853         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8854         {
8855                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8856                 assert_eq!(added_monitors.len(), 1);
8857                 assert_eq!(added_monitors[0].0, funding_output);
8858                 added_monitors.clear();
8859         }
8860         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8861
8862         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8863
8864         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8865         let channel_id = funding_outpoint.to_channel_id();
8866
8867         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8868         // temporary one).
8869
8870         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8871         // Technically this is allowed by the spec, but we don't support it and there's little reason
8872         // to. Still, it shouldn't cause any other issues.
8873         open_chan_msg.temporary_channel_id = channel_id;
8874         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8875         {
8876                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8877                 assert_eq!(events.len(), 1);
8878                 match events[0] {
8879                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8880                                 // Technically, at this point, nodes[1] would be justified in thinking both
8881                                 // channels are closed, but currently we do not, so we just move forward with it.
8882                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8883                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8884                         },
8885                         _ => panic!("Unexpected event"),
8886                 }
8887         }
8888
8889         // Now try to create a second channel which has a duplicate funding output.
8890         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8891         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8892         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8893         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8894         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8895
8896         let funding_created = {
8897                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8898                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8899                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8900                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8901                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8902                 // channelmanager in a possibly nonsense state instead).
8903                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8904                 let logger = test_utils::TestLogger::new();
8905                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8906         };
8907         check_added_monitors!(nodes[0], 0);
8908         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8909         // At this point we'll look up if the channel_id is present and immediately fail the channel
8910         // without trying to persist the `ChannelMonitor`.
8911         check_added_monitors!(nodes[1], 0);
8912
8913         // ...still, nodes[1] will reject the duplicate channel.
8914         {
8915                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8916                 assert_eq!(events.len(), 1);
8917                 match events[0] {
8918                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8919                                 // Technically, at this point, nodes[1] would be justified in thinking both
8920                                 // channels are closed, but currently we do not, so we just move forward with it.
8921                                 assert_eq!(msg.channel_id, channel_id);
8922                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8923                         },
8924                         _ => panic!("Unexpected event"),
8925                 }
8926         }
8927
8928         // finally, finish creating the original channel and send a payment over it to make sure
8929         // everything is functional.
8930         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8931         {
8932                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8933                 assert_eq!(added_monitors.len(), 1);
8934                 assert_eq!(added_monitors[0].0, funding_output);
8935                 added_monitors.clear();
8936         }
8937         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8938
8939         let events_4 = nodes[0].node.get_and_clear_pending_events();
8940         assert_eq!(events_4.len(), 0);
8941         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8942         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8943
8944         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8945         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8946         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8947
8948         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8949 }
8950
8951 #[test]
8952 fn test_error_chans_closed() {
8953         // Test that we properly handle error messages, closing appropriate channels.
8954         //
8955         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8956         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8957         // we can test various edge cases around it to ensure we don't regress.
8958         let chanmon_cfgs = create_chanmon_cfgs(3);
8959         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8960         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8961         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8962
8963         // Create some initial channels
8964         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8965         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8966         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8967
8968         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8969         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8970         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8971
8972         // Closing a channel from a different peer has no effect
8973         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8974         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8975
8976         // Closing one channel doesn't impact others
8977         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8978         check_added_monitors!(nodes[0], 1);
8979         check_closed_broadcast!(nodes[0], false);
8980         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8981         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8982         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8983         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_1.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_1.2);
8984         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_3.2);
8985
8986         // A null channel ID should close all channels
8987         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8988         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8989         check_added_monitors!(nodes[0], 2);
8990         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8991         let events = nodes[0].node.get_and_clear_pending_msg_events();
8992         assert_eq!(events.len(), 2);
8993         match events[0] {
8994                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8995                         assert_eq!(msg.contents.flags & 2, 2);
8996                 },
8997                 _ => panic!("Unexpected event"),
8998         }
8999         match events[1] {
9000                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9001                         assert_eq!(msg.contents.flags & 2, 2);
9002                 },
9003                 _ => panic!("Unexpected event"),
9004         }
9005         // Note that at this point users of a standard PeerHandler will end up calling
9006         // peer_disconnected.
9007         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9008         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9009
9010         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9011         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9012         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9013 }
9014
9015 #[test]
9016 fn test_invalid_funding_tx() {
9017         // Test that we properly handle invalid funding transactions sent to us from a peer.
9018         //
9019         // Previously, all other major lightning implementations had failed to properly sanitize
9020         // funding transactions from their counterparties, leading to a multi-implementation critical
9021         // security vulnerability (though we always sanitized properly, we've previously had
9022         // un-released crashes in the sanitization process).
9023         //
9024         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9025         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9026         // gave up on it. We test this here by generating such a transaction.
9027         let chanmon_cfgs = create_chanmon_cfgs(2);
9028         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9029         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9030         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9031
9032         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9033         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9034         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9035
9036         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9037
9038         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9039         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9040         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9041         // its length.
9042         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9043         let wit_program_script: Script = wit_program.into();
9044         for output in tx.output.iter_mut() {
9045                 // Make the confirmed funding transaction have a bogus script_pubkey
9046                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9047         }
9048
9049         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9050         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9051         check_added_monitors!(nodes[1], 1);
9052         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9053
9054         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9055         check_added_monitors!(nodes[0], 1);
9056         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9057
9058         let events_1 = nodes[0].node.get_and_clear_pending_events();
9059         assert_eq!(events_1.len(), 0);
9060
9061         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9062         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9063         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9064
9065         let expected_err = "funding tx had wrong script/value or output index";
9066         confirm_transaction_at(&nodes[1], &tx, 1);
9067         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9068         check_added_monitors!(nodes[1], 1);
9069         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9070         assert_eq!(events_2.len(), 1);
9071         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9072                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9073                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9074                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9075                 } else { panic!(); }
9076         } else { panic!(); }
9077         assert_eq!(nodes[1].node.list_channels().len(), 0);
9078
9079         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9080         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9081         // as its not 32 bytes long.
9082         let mut spend_tx = Transaction {
9083                 version: 2i32, lock_time: PackedLockTime::ZERO,
9084                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9085                         previous_output: BitcoinOutPoint {
9086                                 txid: tx.txid(),
9087                                 vout: idx as u32,
9088                         },
9089                         script_sig: Script::new(),
9090                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9091                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9092                 }).collect(),
9093                 output: vec![TxOut {
9094                         value: 1000,
9095                         script_pubkey: Script::new(),
9096                 }]
9097         };
9098         check_spends!(spend_tx, tx);
9099         mine_transaction(&nodes[1], &spend_tx);
9100 }
9101
9102 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9103         // In the first version of the chain::Confirm interface, after a refactor was made to not
9104         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9105         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9106         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9107         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9108         // spending transaction until height N+1 (or greater). This was due to the way
9109         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9110         // spending transaction at the height the input transaction was confirmed at, not whether we
9111         // should broadcast a spending transaction at the current height.
9112         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9113         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9114         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9115         // until we learned about an additional block.
9116         //
9117         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9118         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9119         let chanmon_cfgs = create_chanmon_cfgs(3);
9120         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9121         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9122         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9123         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9124
9125         create_announced_chan_between_nodes(&nodes, 0, 1);
9126         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9127         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9128         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9129         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9130
9131         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9132         check_closed_broadcast!(nodes[1], true);
9133         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9134         check_added_monitors!(nodes[1], 1);
9135         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9136         assert_eq!(node_txn.len(), 1);
9137
9138         let conf_height = nodes[1].best_block_info().1;
9139         if !test_height_before_timelock {
9140                 connect_blocks(&nodes[1], 24 * 6);
9141         }
9142         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9143                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9144         if test_height_before_timelock {
9145                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9146                 // generate any events or broadcast any transactions
9147                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9148                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9149         } else {
9150                 // We should broadcast an HTLC transaction spending our funding transaction first
9151                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9152                 assert_eq!(spending_txn.len(), 2);
9153                 assert_eq!(spending_txn[0], node_txn[0]);
9154                 check_spends!(spending_txn[1], node_txn[0]);
9155                 // We should also generate a SpendableOutputs event with the to_self output (as its
9156                 // timelock is up).
9157                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9158                 assert_eq!(descriptor_spend_txn.len(), 1);
9159
9160                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9161                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9162                 // additional block built on top of the current chain.
9163                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9164                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9165                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: channel_id }]);
9166                 check_added_monitors!(nodes[1], 1);
9167
9168                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9169                 assert!(updates.update_add_htlcs.is_empty());
9170                 assert!(updates.update_fulfill_htlcs.is_empty());
9171                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9172                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9173                 assert!(updates.update_fee.is_none());
9174                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9175                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9176                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9177         }
9178 }
9179
9180 #[test]
9181 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9182         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9183         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9184 }
9185
9186 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9187         let chanmon_cfgs = create_chanmon_cfgs(2);
9188         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9189         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9190         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9191
9192         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9193
9194         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9195                 .with_features(nodes[1].node.invoice_features());
9196         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9197
9198         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9199
9200         {
9201                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9202                 check_added_monitors!(nodes[0], 1);
9203                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9204                 assert_eq!(events.len(), 1);
9205                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9206                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9207                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9208         }
9209         expect_pending_htlcs_forwardable!(nodes[1]);
9210         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9211
9212         {
9213                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9214                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9215                 check_added_monitors!(nodes[0], 1);
9216                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9217                 assert_eq!(events.len(), 1);
9218                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9219                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9220                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9221                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9222                 // assume the second is a privacy attack (no longer particularly relevant
9223                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9224                 // the first HTLC delivered above.
9225         }
9226
9227         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9228         nodes[1].node.process_pending_htlc_forwards();
9229
9230         if test_for_second_fail_panic {
9231                 // Now we go fail back the first HTLC from the user end.
9232                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9233
9234                 let expected_destinations = vec![
9235                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9236                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9237                 ];
9238                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9239                 nodes[1].node.process_pending_htlc_forwards();
9240
9241                 check_added_monitors!(nodes[1], 1);
9242                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9243                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9244
9245                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9246                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9247                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9248
9249                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9250                 assert_eq!(failure_events.len(), 4);
9251                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9252                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9253                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9254                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9255         } else {
9256                 // Let the second HTLC fail and claim the first
9257                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9258                 nodes[1].node.process_pending_htlc_forwards();
9259
9260                 check_added_monitors!(nodes[1], 1);
9261                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9262                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9263                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9264
9265                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9266
9267                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9268         }
9269 }
9270
9271 #[test]
9272 fn test_dup_htlc_second_fail_panic() {
9273         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9274         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9275         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9276         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9277         do_test_dup_htlc_second_rejected(true);
9278 }
9279
9280 #[test]
9281 fn test_dup_htlc_second_rejected() {
9282         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9283         // simply reject the second HTLC but are still able to claim the first HTLC.
9284         do_test_dup_htlc_second_rejected(false);
9285 }
9286
9287 #[test]
9288 fn test_inconsistent_mpp_params() {
9289         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9290         // such HTLC and allow the second to stay.
9291         let chanmon_cfgs = create_chanmon_cfgs(4);
9292         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9293         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9294         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9295
9296         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9297         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9298         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9299         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9300
9301         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9302                 .with_features(nodes[3].node.invoice_features());
9303         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9304         assert_eq!(route.paths.len(), 2);
9305         route.paths.sort_by(|path_a, _| {
9306                 // Sort the path so that the path through nodes[1] comes first
9307                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9308                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9309         });
9310
9311         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9312
9313         let cur_height = nodes[0].best_block_info().1;
9314         let payment_id = PaymentId([42; 32]);
9315
9316         let session_privs = {
9317                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9318                 // ultimately have, just not right away.
9319                 let mut dup_route = route.clone();
9320                 dup_route.paths.push(route.paths[1].clone());
9321                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9322         };
9323         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9324         check_added_monitors!(nodes[0], 1);
9325
9326         {
9327                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9328                 assert_eq!(events.len(), 1);
9329                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9330         }
9331         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9332
9333         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9334         check_added_monitors!(nodes[0], 1);
9335
9336         {
9337                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9338                 assert_eq!(events.len(), 1);
9339                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9340
9341                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9342                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9343
9344                 expect_pending_htlcs_forwardable!(nodes[2]);
9345                 check_added_monitors!(nodes[2], 1);
9346
9347                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9348                 assert_eq!(events.len(), 1);
9349                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9350
9351                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9352                 check_added_monitors!(nodes[3], 0);
9353                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9354
9355                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9356                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9357                 // post-payment_secrets) and fail back the new HTLC.
9358         }
9359         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9360         nodes[3].node.process_pending_htlc_forwards();
9361         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9362         nodes[3].node.process_pending_htlc_forwards();
9363
9364         check_added_monitors!(nodes[3], 1);
9365
9366         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9367         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9368         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9369
9370         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9371         check_added_monitors!(nodes[2], 1);
9372
9373         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9374         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9375         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9376
9377         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9378
9379         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[2]).unwrap();
9380         check_added_monitors!(nodes[0], 1);
9381
9382         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9383         assert_eq!(events.len(), 1);
9384         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9385
9386         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9387         let events = nodes[0].node.get_and_clear_pending_events();
9388         assert_eq!(events.len(), 3);
9389         match events[0] {
9390                 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9391                         assert_eq!(payment_hash, our_payment_hash);
9392                 },
9393                 _ => panic!("Unexpected event")
9394         }
9395         match events[1] {
9396                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9397                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9398                 },
9399                 _ => panic!("Unexpected event")
9400         }
9401         match events[2] {
9402                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9403                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9404                 },
9405                 _ => panic!("Unexpected event")
9406         }
9407 }
9408
9409 #[test]
9410 fn test_keysend_payments_to_public_node() {
9411         let chanmon_cfgs = create_chanmon_cfgs(2);
9412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9414         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9415
9416         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9417         let network_graph = nodes[0].network_graph.clone();
9418         let payer_pubkey = nodes[0].node.get_our_node_id();
9419         let payee_pubkey = nodes[1].node.get_our_node_id();
9420         let route_params = RouteParameters {
9421                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9422                 final_value_msat: 10000,
9423         };
9424         let scorer = test_utils::TestScorer::new();
9425         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9426         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9427
9428         let test_preimage = PaymentPreimage([42; 32]);
9429         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9430         check_added_monitors!(nodes[0], 1);
9431         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9432         assert_eq!(events.len(), 1);
9433         let event = events.pop().unwrap();
9434         let path = vec![&nodes[1]];
9435         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9436         claim_payment(&nodes[0], &path, test_preimage);
9437 }
9438
9439 #[test]
9440 fn test_keysend_payments_to_private_node() {
9441         let chanmon_cfgs = create_chanmon_cfgs(2);
9442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9445
9446         let payer_pubkey = nodes[0].node.get_our_node_id();
9447         let payee_pubkey = nodes[1].node.get_our_node_id();
9448
9449         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9450         let route_params = RouteParameters {
9451                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9452                 final_value_msat: 10000,
9453         };
9454         let network_graph = nodes[0].network_graph.clone();
9455         let first_hops = nodes[0].node.list_usable_channels();
9456         let scorer = test_utils::TestScorer::new();
9457         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9458         let route = find_route(
9459                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9460                 nodes[0].logger, &scorer, &random_seed_bytes
9461         ).unwrap();
9462
9463         let test_preimage = PaymentPreimage([42; 32]);
9464         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9465         check_added_monitors!(nodes[0], 1);
9466         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9467         assert_eq!(events.len(), 1);
9468         let event = events.pop().unwrap();
9469         let path = vec![&nodes[1]];
9470         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9471         claim_payment(&nodes[0], &path, test_preimage);
9472 }
9473
9474 #[test]
9475 fn test_double_partial_claim() {
9476         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9477         // time out, the sender resends only some of the MPP parts, then the user processes the
9478         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9479         // amount.
9480         let chanmon_cfgs = create_chanmon_cfgs(4);
9481         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9482         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9483         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9484
9485         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9486         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9487         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9488         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9489
9490         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9491         assert_eq!(route.paths.len(), 2);
9492         route.paths.sort_by(|path_a, _| {
9493                 // Sort the path so that the path through nodes[1] comes first
9494                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9495                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9496         });
9497
9498         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9499         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9500         // amount of time to respond to.
9501
9502         // Connect some blocks to time out the payment
9503         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9504         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9505
9506         let failed_destinations = vec![
9507                 HTLCDestination::FailedPayment { payment_hash },
9508                 HTLCDestination::FailedPayment { payment_hash },
9509         ];
9510         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9511
9512         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9513
9514         // nodes[1] now retries one of the two paths...
9515         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9516         check_added_monitors!(nodes[0], 2);
9517
9518         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9519         assert_eq!(events.len(), 2);
9520         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9521         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9522
9523         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9524         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9525         nodes[3].node.claim_funds(payment_preimage);
9526         check_added_monitors!(nodes[3], 0);
9527         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9528 }
9529
9530 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9531 #[derive(Clone, Copy, PartialEq)]
9532 enum ExposureEvent {
9533         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9534         AtHTLCForward,
9535         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9536         AtHTLCReception,
9537         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9538         AtUpdateFeeOutbound,
9539 }
9540
9541 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9542         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9543         // policy.
9544         //
9545         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9546         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9547         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9548         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9549         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9550         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9551         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9552         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9553
9554         let chanmon_cfgs = create_chanmon_cfgs(2);
9555         let mut config = test_default_channel_config();
9556         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9559         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9560
9561         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9562         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9563         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9564         open_channel.max_accepted_htlcs = 60;
9565         if on_holder_tx {
9566                 open_channel.dust_limit_satoshis = 546;
9567         }
9568         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9569         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9570         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9571
9572         let opt_anchors = false;
9573
9574         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9575
9576         if on_holder_tx {
9577                 let mut node_0_per_peer_lock;
9578                 let mut node_0_peer_state_lock;
9579                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9580                 chan.holder_dust_limit_satoshis = 546;
9581         }
9582
9583         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9584         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9585         check_added_monitors!(nodes[1], 1);
9586         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9587
9588         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9589         check_added_monitors!(nodes[0], 1);
9590         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9591
9592         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9593         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9594         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9595
9596         let dust_buffer_feerate = {
9597                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9598                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9599                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9600                 chan.get_dust_buffer_feerate(None) as u64
9601         };
9602         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9603         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9604
9605         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9606         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9607
9608         let dust_htlc_on_counterparty_tx: u64 = 25;
9609         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9610
9611         if on_holder_tx {
9612                 if dust_outbound_balance {
9613                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9614                         // Outbound dust balance: 4372 sats
9615                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9616                         for i in 0..dust_outbound_htlc_on_holder_tx {
9617                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9618                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9619                         }
9620                 } else {
9621                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9622                         // Inbound dust balance: 4372 sats
9623                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9624                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9625                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9626                         }
9627                 }
9628         } else {
9629                 if dust_outbound_balance {
9630                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9631                         // Outbound dust balance: 5000 sats
9632                         for i in 0..dust_htlc_on_counterparty_tx {
9633                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9634                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9635                         }
9636                 } else {
9637                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9638                         // Inbound dust balance: 5000 sats
9639                         for _ in 0..dust_htlc_on_counterparty_tx {
9640                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9641                         }
9642                 }
9643         }
9644
9645         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9646         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9647                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9648                 let mut config = UserConfig::default();
9649                 // With default dust exposure: 5000 sats
9650                 if on_holder_tx {
9651                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9652                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9653                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9654                 } else {
9655                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9656                 }
9657         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9658                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9659                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9660                 check_added_monitors!(nodes[1], 1);
9661                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9662                 assert_eq!(events.len(), 1);
9663                 let payment_event = SendEvent::from_event(events.remove(0));
9664                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9665                 // With default dust exposure: 5000 sats
9666                 if on_holder_tx {
9667                         // Outbound dust balance: 6399 sats
9668                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9669                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9670                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat), 1);
9671                 } else {
9672                         // Outbound dust balance: 5200 sats
9673                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9674                 }
9675         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9676                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9677                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9678                 {
9679                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9680                         *feerate_lock = *feerate_lock * 10;
9681                 }
9682                 nodes[0].node.timer_tick_occurred();
9683                 check_added_monitors!(nodes[0], 1);
9684                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9685         }
9686
9687         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9688         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9689         added_monitors.clear();
9690 }
9691
9692 #[test]
9693 fn test_max_dust_htlc_exposure() {
9694         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9695         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9696         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9697         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9698         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9699         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9700         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9701         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9702         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9703         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9704         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9705         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9706 }
9707
9708 #[test]
9709 fn test_non_final_funding_tx() {
9710         let chanmon_cfgs = create_chanmon_cfgs(2);
9711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9714
9715         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9716         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9717         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9718         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9719         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9720
9721         let best_height = nodes[0].node.best_block.read().unwrap().height();
9722
9723         let chan_id = *nodes[0].network_chan_count.borrow();
9724         let events = nodes[0].node.get_and_clear_pending_events();
9725         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9726         assert_eq!(events.len(), 1);
9727         let mut tx = match events[0] {
9728                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9729                         // Timelock the transaction _beyond_ the best client height + 2.
9730                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9731                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9732                         }]}
9733                 },
9734                 _ => panic!("Unexpected event"),
9735         };
9736         // Transaction should fail as it's evaluated as non-final for propagation.
9737         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9738                 Err(APIError::APIMisuseError { err }) => {
9739                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9740                 },
9741                 _ => panic!()
9742         }
9743
9744         // However, transaction should be accepted if it's in a +2 headroom from best block.
9745         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9746         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9747         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9748 }
9749
9750 #[test]
9751 fn accept_busted_but_better_fee() {
9752         // If a peer sends us a fee update that is too low, but higher than our previous channel
9753         // feerate, we should accept it. In the future we may want to consider closing the channel
9754         // later, but for now we only accept the update.
9755         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9756         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9757         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9758         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9759
9760         create_chan_between_nodes(&nodes[0], &nodes[1]);
9761
9762         // Set nodes[1] to expect 5,000 sat/kW.
9763         {
9764                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9765                 *feerate_lock = 5000;
9766         }
9767
9768         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9769         {
9770                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9771                 *feerate_lock = 1000;
9772         }
9773         nodes[0].node.timer_tick_occurred();
9774         check_added_monitors!(nodes[0], 1);
9775
9776         let events = nodes[0].node.get_and_clear_pending_msg_events();
9777         assert_eq!(events.len(), 1);
9778         match events[0] {
9779                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9780                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9781                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9782                 },
9783                 _ => panic!("Unexpected event"),
9784         };
9785
9786         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9787         // it.
9788         {
9789                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9790                 *feerate_lock = 2000;
9791         }
9792         nodes[0].node.timer_tick_occurred();
9793         check_added_monitors!(nodes[0], 1);
9794
9795         let events = nodes[0].node.get_and_clear_pending_msg_events();
9796         assert_eq!(events.len(), 1);
9797         match events[0] {
9798                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9799                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9800                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9801                 },
9802                 _ => panic!("Unexpected event"),
9803         };
9804
9805         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9806         // channel.
9807         {
9808                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9809                 *feerate_lock = 1000;
9810         }
9811         nodes[0].node.timer_tick_occurred();
9812         check_added_monitors!(nodes[0], 1);
9813
9814         let events = nodes[0].node.get_and_clear_pending_msg_events();
9815         assert_eq!(events.len(), 1);
9816         match events[0] {
9817                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9818                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9819                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9820                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9821                         check_closed_broadcast!(nodes[1], true);
9822                         check_added_monitors!(nodes[1], 1);
9823                 },
9824                 _ => panic!("Unexpected event"),
9825         };
9826 }
9827
9828 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9829         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9830         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9831         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9832         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9833         let min_final_cltv_expiry_delta = 120;
9834         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9835                 min_final_cltv_expiry_delta - 2 };
9836         let recv_value = 100_000;
9837
9838         create_chan_between_nodes(&nodes[0], &nodes[1]);
9839
9840         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9841         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9842                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9843                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9844                 (payment_hash, payment_preimage, payment_secret)
9845         } else {
9846                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9847                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9848         };
9849         let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9850         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9851         check_added_monitors!(nodes[0], 1);
9852         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9853         assert_eq!(events.len(), 1);
9854         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9855         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9856         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9857         expect_pending_htlcs_forwardable!(nodes[1]);
9858
9859         if valid_delta {
9860                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9861                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9862
9863                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9864         } else {
9865                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9866
9867                 check_added_monitors!(nodes[1], 1);
9868
9869                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9870                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9871                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9872
9873                 expect_payment_failed!(nodes[0], payment_hash, true);
9874         }
9875 }
9876
9877 #[test]
9878 fn test_payment_with_custom_min_cltv_expiry_delta() {
9879         do_payment_with_custom_min_final_cltv_expiry(false, false);
9880         do_payment_with_custom_min_final_cltv_expiry(false, true);
9881         do_payment_with_custom_min_final_cltv_expiry(true, false);
9882         do_payment_with_custom_min_final_cltv_expiry(true, true);
9883 }