]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
Merge pull request #2226 from alecchendev/2023-04-persist-network-graph-on-rgs
[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::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
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, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, 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::{Path, 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::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         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 });
108         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 });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         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 });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         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 });
117
118         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 });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let opt_anchors = false;
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         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();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
177         {
178                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180                 let mut sender_node_per_peer_lock;
181                 let mut sender_node_peer_state_lock;
182                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183                 chan.holder_selected_channel_reserve_satoshis = 0;
184                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
185         }
186
187         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
190
191         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193         if send_from_initiator {
194                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195                         // Note that for outbound channels we have to consider the commitment tx fee and the
196                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197                         // well as an additional HTLC.
198                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
199         } else {
200                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
201         }
202 }
203
204 #[test]
205 fn test_counterparty_no_reserve() {
206         do_test_counterparty_no_reserve(true);
207         do_test_counterparty_no_reserve(false);
208 }
209
210 #[test]
211 fn test_async_inbound_update_fee() {
212         let chanmon_cfgs = create_chanmon_cfgs(2);
213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216         create_announced_chan_between_nodes(&nodes, 0, 1);
217
218         // balancing
219         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220
221         // A                                        B
222         // update_fee                            ->
223         // send (1) commitment_signed            -.
224         //                                       <- update_add_htlc/commitment_signed
225         // send (2) RAA (awaiting remote revoke) -.
226         // (1) commitment_signed is delivered    ->
227         //                                       .- send (3) RAA (awaiting remote revoke)
228         // (2) RAA is delivered                  ->
229         //                                       .- send (4) commitment_signed
230         //                                       <- (3) RAA is delivered
231         // send (5) commitment_signed            -.
232         //                                       <- (4) commitment_signed is delivered
233         // send (6) RAA                          -.
234         // (5) commitment_signed is delivered    ->
235         //                                       <- RAA
236         // (6) RAA is delivered                  ->
237
238         // First nodes[0] generates an update_fee
239         {
240                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
241                 *feerate_lock += 20;
242         }
243         nodes[0].node.timer_tick_occurred();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let (update_msg, commitment_signed) = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250                         (update_fee.as_ref(), commitment_signed)
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260                 RecipientOnionFields::secret_only(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_with_route(&route, our_payment_hash,
360                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361         check_added_monitors!(nodes[1], 1);
362
363         let payment_event = {
364                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365                 assert_eq!(events_1.len(), 1);
366                 SendEvent::from_event(events_1.remove(0))
367         };
368         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369         assert_eq!(payment_event.msgs.len(), 1);
370
371         // ...now when the messages get delivered everyone should be happy
372         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376         check_added_monitors!(nodes[0], 1);
377
378         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379         check_added_monitors!(nodes[1], 1);
380
381         // We can't continue, sadly, because our (1) now has a bogus signature
382 }
383
384 #[test]
385 fn test_multi_flight_update_fee() {
386         let chanmon_cfgs = create_chanmon_cfgs(2);
387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390         create_announced_chan_between_nodes(&nodes, 0, 1);
391
392         // A                                        B
393         // update_fee/commitment_signed          ->
394         //                                       .- send (1) RAA and (2) commitment_signed
395         // update_fee (never committed)          ->
396         // (3) update_fee                        ->
397         // We have to manually generate the above update_fee, it is allowed by the protocol but we
398         // don't track which updates correspond to which revoke_and_ack responses so we're in
399         // AwaitingRAA mode and will not generate the update_fee yet.
400         //                                       <- (1) RAA delivered
401         // (3) is generated and send (4) CS      -.
402         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403         // know the per_commitment_point to use for it.
404         //                                       <- (2) commitment_signed delivered
405         // revoke_and_ack                        ->
406         //                                          B should send no response here
407         // (4) commitment_signed delivered       ->
408         //                                       <- RAA/commitment_signed delivered
409         // revoke_and_ack                        ->
410
411         // First nodes[0] generates an update_fee
412         let initial_feerate;
413         {
414                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415                 initial_feerate = *feerate_lock;
416                 *feerate_lock = initial_feerate + 20;
417         }
418         nodes[0].node.timer_tick_occurred();
419         check_added_monitors!(nodes[0], 1);
420
421         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422         assert_eq!(events_0.len(), 1);
423         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425                         (update_fee.as_ref().unwrap(), commitment_signed)
426                 },
427                 _ => panic!("Unexpected event"),
428         };
429
430         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434         check_added_monitors!(nodes[1], 1);
435
436         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
437         // transaction:
438         {
439                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440                 *feerate_lock = initial_feerate + 40;
441         }
442         nodes[0].node.timer_tick_occurred();
443         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
445
446         // Create the (3) update_fee message that nodes[0] will generate before it does...
447         let mut update_msg_2 = msgs::UpdateFee {
448                 channel_id: update_msg_1.channel_id.clone(),
449                 feerate_per_kw: (initial_feerate + 30) as u32,
450         };
451
452         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
453
454         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
455         // Deliver (3)
456         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
457
458         // Deliver (1), generating (3) and (4)
459         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461         check_added_monitors!(nodes[0], 1);
462         assert!(as_second_update.update_add_htlcs.is_empty());
463         assert!(as_second_update.update_fulfill_htlcs.is_empty());
464         assert!(as_second_update.update_fail_htlcs.is_empty());
465         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466         // Check that the update_fee newly generated matches what we delivered:
467         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
469
470         // Deliver (2) commitment_signed
471         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473         check_added_monitors!(nodes[0], 1);
474         // No commitment_signed so get_event_msg's assert(len == 1) passes
475
476         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478         check_added_monitors!(nodes[1], 1);
479
480         // Delever (4)
481         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483         check_added_monitors!(nodes[1], 1);
484
485         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487         check_added_monitors!(nodes[0], 1);
488
489         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491         // No commitment_signed so get_event_msg's assert(len == 1) passes
492         check_added_monitors!(nodes[0], 1);
493
494         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496         check_added_monitors!(nodes[1], 1);
497 }
498
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500         // Previously, we had issues deserializing channels when we hadn't connected the first block
501         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502         // serialization round-trips and simply do steps towards opening a channel and then drop the
503         // Node objects.
504
505         let chanmon_cfgs = create_chanmon_cfgs(2);
506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
509
510         if steps & 0b1000_0000 != 0{
511                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512                 connect_block(&nodes[0], &block);
513                 connect_block(&nodes[1], &block);
514         }
515
516         if steps & 0x0f == 0 { return; }
517         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
519
520         if steps & 0x0f == 1 { return; }
521         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
523
524         if steps & 0x0f == 2 { return; }
525         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
526
527         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
528
529         if steps & 0x0f == 3 { return; }
530         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531         check_added_monitors!(nodes[0], 0);
532         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
533
534         if steps & 0x0f == 4 { return; }
535         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
536         {
537                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538                 assert_eq!(added_monitors.len(), 1);
539                 assert_eq!(added_monitors[0].0, funding_output);
540                 added_monitors.clear();
541         }
542         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
543
544         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
545
546         if steps & 0x0f == 5 { return; }
547         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
548         {
549                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550                 assert_eq!(added_monitors.len(), 1);
551                 assert_eq!(added_monitors[0].0, funding_output);
552                 added_monitors.clear();
553         }
554
555         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556         let events_4 = nodes[0].node.get_and_clear_pending_events();
557         assert_eq!(events_4.len(), 0);
558
559         if steps & 0x0f == 6 { return; }
560         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
561
562         if steps & 0x0f == 7 { return; }
563         confirm_transaction_at(&nodes[0], &tx, 2);
564         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
567 }
568
569 #[test]
570 fn test_sanity_on_in_flight_opens() {
571         do_test_sanity_on_in_flight_opens(0);
572         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(1);
574         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(2);
576         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(3);
578         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(4);
580         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(5);
582         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(6);
584         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(7);
586         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(8);
588         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
589 }
590
591 #[test]
592 fn test_update_fee_vanilla() {
593         let chanmon_cfgs = create_chanmon_cfgs(2);
594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597         create_announced_chan_between_nodes(&nodes, 0, 1);
598
599         {
600                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
601                 *feerate_lock += 25;
602         }
603         nodes[0].node.timer_tick_occurred();
604         check_added_monitors!(nodes[0], 1);
605
606         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607         assert_eq!(events_0.len(), 1);
608         let (update_msg, commitment_signed) = match events_0[0] {
609                         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 } } => {
610                         (update_fee.as_ref(), commitment_signed)
611                 },
612                 _ => panic!("Unexpected event"),
613         };
614         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
615
616         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618         check_added_monitors!(nodes[1], 1);
619
620         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622         check_added_monitors!(nodes[0], 1);
623
624         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626         // No commitment_signed so get_event_msg's assert(len == 1) passes
627         check_added_monitors!(nodes[0], 1);
628
629         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631         check_added_monitors!(nodes[1], 1);
632 }
633
634 #[test]
635 fn test_update_fee_that_funder_cannot_afford() {
636         let chanmon_cfgs = create_chanmon_cfgs(2);
637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640         let channel_value = 5000;
641         let push_sats = 700;
642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643         let channel_id = chan.2;
644         let secp_ctx = Secp256k1::new();
645         let default_config = UserConfig::default();
646         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
647
648         let opt_anchors = false;
649
650         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652         // calculate two different feerates here - the expected local limit as well as the expected
653         // remote limit.
654         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;
655         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
656         {
657                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658                 *feerate_lock = feerate;
659         }
660         nodes[0].node.timer_tick_occurred();
661         check_added_monitors!(nodes[0], 1);
662         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
663
664         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
665
666         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
667
668         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
669         {
670                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
671
672                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673                 assert_eq!(commitment_tx.output.len(), 2);
674                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676                 actual_fee = channel_value - actual_fee;
677                 assert_eq!(total_fee, actual_fee);
678         }
679
680         {
681                 // Increment the feerate by a small constant, accounting for rounding errors
682                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
683                 *feerate_lock += 4;
684         }
685         nodes[0].node.timer_tick_occurred();
686         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687         check_added_monitors!(nodes[0], 0);
688
689         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
690
691         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692         // needed to sign the new commitment tx and (2) sign the new commitment tx.
693         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697                 let chan_signer = local_chan.get_signer();
698                 let pubkeys = chan_signer.pubkeys();
699                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700                  pubkeys.funding_pubkey)
701         };
702         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706                 let chan_signer = remote_chan.get_signer();
707                 let pubkeys = chan_signer.pubkeys();
708                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710                  pubkeys.funding_pubkey)
711         };
712
713         // Assemble the set of keys we can use for signatures for our commitment_signed message.
714         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
716
717         let res = {
718                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721                 let local_chan_signer = local_chan.get_signer();
722                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724                         INITIAL_COMMITMENT_NUMBER - 1,
725                         push_sats,
726                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727                         opt_anchors, local_funding, remote_funding,
728                         commit_tx_keys.clone(),
729                         non_buffer_feerate + 4,
730                         &mut htlcs,
731                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
732                 );
733                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
734         };
735
736         let commit_signed_msg = msgs::CommitmentSigned {
737                 channel_id: chan.2,
738                 signature: res.0,
739                 htlc_signatures: res.1,
740                 #[cfg(taproot)]
741                 partial_signature_with_nonce: None,
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_with_route(&route, our_payment_hash,
796                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
797         {
798                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799                 assert_eq!(added_monitors.len(), 0);
800                 added_monitors.clear();
801         }
802         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804         // node[1] has nothing to do
805
806         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808         check_added_monitors!(nodes[0], 1);
809
810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812         // No commitment_signed so get_event_msg's assert(len == 1) passes
813         check_added_monitors!(nodes[0], 1);
814         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815         check_added_monitors!(nodes[1], 1);
816         // AwaitingRemoteRevoke ends here
817
818         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823         assert_eq!(commitment_update.update_fee.is_none(), true);
824
825         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827         check_added_monitors!(nodes[0], 1);
828         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
829
830         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831         check_added_monitors!(nodes[1], 1);
832         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
833
834         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835         check_added_monitors!(nodes[1], 1);
836         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837         // No commitment_signed so get_event_msg's assert(len == 1) passes
838
839         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840         check_added_monitors!(nodes[0], 1);
841         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
842
843         expect_pending_htlcs_forwardable!(nodes[0]);
844
845         let events = nodes[0].node.get_and_clear_pending_events();
846         assert_eq!(events.len(), 1);
847         match events[0] {
848                 Event::PaymentClaimable { .. } => { },
849                 _ => panic!("Unexpected event"),
850         };
851
852         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
853
854         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
859 }
860
861 #[test]
862 fn test_update_fee() {
863         let chanmon_cfgs = create_chanmon_cfgs(2);
864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868         let channel_id = chan.2;
869
870         // A                                        B
871         // (1) update_fee/commitment_signed      ->
872         //                                       <- (2) revoke_and_ack
873         //                                       .- send (3) commitment_signed
874         // (4) update_fee/commitment_signed      ->
875         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876         //                                       <- (3) commitment_signed delivered
877         // send (6) revoke_and_ack               -.
878         //                                       <- (5) deliver revoke_and_ack
879         // (6) deliver revoke_and_ack            ->
880         //                                       .- send (7) commitment_signed in response to (4)
881         //                                       <- (7) deliver commitment_signed
882         // revoke_and_ack                        ->
883
884         // Create and deliver (1)...
885         let feerate;
886         {
887                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888                 feerate = *feerate_lock;
889                 *feerate_lock = feerate + 20;
890         }
891         nodes[0].node.timer_tick_occurred();
892         check_added_monitors!(nodes[0], 1);
893
894         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895         assert_eq!(events_0.len(), 1);
896         let (update_msg, commitment_signed) = match events_0[0] {
897                         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 } } => {
898                         (update_fee.as_ref(), commitment_signed)
899                 },
900                 _ => panic!("Unexpected event"),
901         };
902         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
903
904         // Generate (2) and (3):
905         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907         check_added_monitors!(nodes[1], 1);
908
909         // Deliver (2):
910         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912         check_added_monitors!(nodes[0], 1);
913
914         // Create and deliver (4)...
915         {
916                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917                 *feerate_lock = feerate + 30;
918         }
919         nodes[0].node.timer_tick_occurred();
920         check_added_monitors!(nodes[0], 1);
921         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922         assert_eq!(events_0.len(), 1);
923         let (update_msg, commitment_signed) = match events_0[0] {
924                         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 } } => {
925                         (update_fee.as_ref(), commitment_signed)
926                 },
927                 _ => panic!("Unexpected event"),
928         };
929
930         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932         check_added_monitors!(nodes[1], 1);
933         // ... creating (5)
934         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935         // No commitment_signed so get_event_msg's assert(len == 1) passes
936
937         // Handle (3), creating (6):
938         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939         check_added_monitors!(nodes[0], 1);
940         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941         // No commitment_signed so get_event_msg's assert(len == 1) passes
942
943         // Deliver (5):
944         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946         check_added_monitors!(nodes[0], 1);
947
948         // Deliver (6), creating (7):
949         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951         assert!(commitment_update.update_add_htlcs.is_empty());
952         assert!(commitment_update.update_fulfill_htlcs.is_empty());
953         assert!(commitment_update.update_fail_htlcs.is_empty());
954         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955         assert!(commitment_update.update_fee.is_none());
956         check_added_monitors!(nodes[1], 1);
957
958         // Deliver (7)
959         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960         check_added_monitors!(nodes[0], 1);
961         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962         // No commitment_signed so get_event_msg's assert(len == 1) passes
963
964         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965         check_added_monitors!(nodes[1], 1);
966         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
967
968         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
973 }
974
975 #[test]
976 fn fake_network_test() {
977         // Simple test which builds a network of ChannelManagers, connects them to each other, and
978         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979         let chanmon_cfgs = create_chanmon_cfgs(4);
980         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
983
984         // Create some initial channels
985         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
988
989         // Rebalance the network a bit by relaying one payment through all the channels...
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         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
994
995         // Send some more payments
996         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
999
1000         // Test failure packets
1001         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1003
1004         // Add a new channel that skips 3
1005         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1006
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1014
1015         // Do some rebalance loop payments, simultaneously
1016         let mut hops = Vec::with_capacity(3);
1017         hops.push(RouteHop {
1018                 pubkey: nodes[2].node.get_our_node_id(),
1019                 node_features: NodeFeatures::empty(),
1020                 short_channel_id: chan_2.0.contents.short_channel_id,
1021                 channel_features: ChannelFeatures::empty(),
1022                 fee_msat: 0,
1023                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1024         });
1025         hops.push(RouteHop {
1026                 pubkey: nodes[3].node.get_our_node_id(),
1027                 node_features: NodeFeatures::empty(),
1028                 short_channel_id: chan_3.0.contents.short_channel_id,
1029                 channel_features: ChannelFeatures::empty(),
1030                 fee_msat: 0,
1031                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1032         });
1033         hops.push(RouteHop {
1034                 pubkey: nodes[1].node.get_our_node_id(),
1035                 node_features: nodes[1].node.node_features(),
1036                 short_channel_id: chan_4.0.contents.short_channel_id,
1037                 channel_features: nodes[1].node.channel_features(),
1038                 fee_msat: 1000000,
1039                 cltv_expiry_delta: TEST_FINAL_CLTV,
1040         });
1041         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;
1042         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;
1043         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1044
1045         let mut hops = Vec::with_capacity(3);
1046         hops.push(RouteHop {
1047                 pubkey: nodes[3].node.get_our_node_id(),
1048                 node_features: NodeFeatures::empty(),
1049                 short_channel_id: chan_4.0.contents.short_channel_id,
1050                 channel_features: ChannelFeatures::empty(),
1051                 fee_msat: 0,
1052                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1053         });
1054         hops.push(RouteHop {
1055                 pubkey: nodes[2].node.get_our_node_id(),
1056                 node_features: NodeFeatures::empty(),
1057                 short_channel_id: chan_3.0.contents.short_channel_id,
1058                 channel_features: ChannelFeatures::empty(),
1059                 fee_msat: 0,
1060                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1061         });
1062         hops.push(RouteHop {
1063                 pubkey: nodes[1].node.get_our_node_id(),
1064                 node_features: nodes[1].node.node_features(),
1065                 short_channel_id: chan_2.0.contents.short_channel_id,
1066                 channel_features: nodes[1].node.channel_features(),
1067                 fee_msat: 1000000,
1068                 cltv_expiry_delta: TEST_FINAL_CLTV,
1069         });
1070         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;
1071         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;
1072         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1073
1074         // Claim the rebalances...
1075         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1077
1078         // Close down the channels...
1079         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091 }
1092
1093 #[test]
1094 fn holding_cell_htlc_counting() {
1095         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097         // commitment dance rounds.
1098         let chanmon_cfgs = create_chanmon_cfgs(3);
1099         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102         create_announced_chan_between_nodes(&nodes, 0, 1);
1103         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1104
1105         let mut payments = Vec::new();
1106         for _ in 0..50 {
1107                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1109                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1110                 payments.push((payment_preimage, payment_hash));
1111         }
1112         check_added_monitors!(nodes[1], 1);
1113
1114         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1115         assert_eq!(events.len(), 1);
1116         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1117         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1118
1119         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1120         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1121         // another HTLC.
1122         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1123         {
1124                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1125                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1126                         ), true, APIError::ChannelUnavailable { ref err },
1127                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1130         }
1131
1132         // This should also be true if we try to forward a payment.
1133         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1134         {
1135                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137                 check_added_monitors!(nodes[0], 1);
1138         }
1139
1140         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141         assert_eq!(events.len(), 1);
1142         let payment_event = SendEvent::from_event(events.pop().unwrap());
1143         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1144
1145         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148         // fails), the second will process the resulting failure and fail the HTLC backward.
1149         expect_pending_htlcs_forwardable!(nodes[1]);
1150         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 }]);
1151         check_added_monitors!(nodes[1], 1);
1152
1153         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1156
1157         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1158
1159         // Now forward all the pending HTLCs and claim them back
1160         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162         check_added_monitors!(nodes[2], 1);
1163
1164         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166         check_added_monitors!(nodes[1], 1);
1167         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1168
1169         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172
1173         for ref update in as_updates.update_add_htlcs.iter() {
1174                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1175         }
1176         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177         check_added_monitors!(nodes[2], 1);
1178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179         check_added_monitors!(nodes[2], 1);
1180         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1181
1182         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183         check_added_monitors!(nodes[1], 1);
1184         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185         check_added_monitors!(nodes[1], 1);
1186         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1187
1188         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189         check_added_monitors!(nodes[2], 1);
1190
1191         expect_pending_htlcs_forwardable!(nodes[2]);
1192
1193         let events = nodes[2].node.get_and_clear_pending_events();
1194         assert_eq!(events.len(), payments.len());
1195         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1196                 match event {
1197                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1198                                 assert_eq!(*payment_hash, *hash);
1199                         },
1200                         _ => panic!("Unexpected event"),
1201                 };
1202         }
1203
1204         for (preimage, _) in payments.drain(..) {
1205                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1206         }
1207
1208         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1209 }
1210
1211 #[test]
1212 fn duplicate_htlc_test() {
1213         // Test that we accept duplicate payment_hash HTLCs across the network and that
1214         // claiming/failing them are all separate and don't affect each other
1215         let chanmon_cfgs = create_chanmon_cfgs(6);
1216         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1219
1220         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221         create_announced_chan_between_nodes(&nodes, 0, 3);
1222         create_announced_chan_between_nodes(&nodes, 1, 3);
1223         create_announced_chan_between_nodes(&nodes, 2, 3);
1224         create_announced_chan_between_nodes(&nodes, 3, 4);
1225         create_announced_chan_between_nodes(&nodes, 3, 5);
1226
1227         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1228
1229         *nodes[0].network_payment_count.borrow_mut() -= 1;
1230         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1231
1232         *nodes[0].network_payment_count.borrow_mut() -= 1;
1233         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1234
1235         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1238 }
1239
1240 #[test]
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242         // Test that ChannelMonitor doesn't generate 2 preimage txn
1243         // when we have 2 HTLCs with same preimage that go across a node
1244         // in opposite directions, even with the same payment secret.
1245         let chanmon_cfgs = create_chanmon_cfgs(2);
1246         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1249
1250         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1251
1252         // balancing
1253         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1254
1255         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1256
1257         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1260
1261         // Provide preimage to node 0 by claiming payment
1262         nodes[0].node.claim_funds(payment_preimage);
1263         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264         check_added_monitors!(nodes[0], 1);
1265
1266         // Broadcast node 1 commitment txn
1267         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1268
1269         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270         let mut has_both_htlcs = 0; // check htlcs match ones committed
1271         for outp in remote_txn[0].output.iter() {
1272                 if outp.value == 800_000 / 1000 {
1273                         has_both_htlcs += 1;
1274                 } else if outp.value == 900_000 / 1000 {
1275                         has_both_htlcs += 1;
1276                 }
1277         }
1278         assert_eq!(has_both_htlcs, 2);
1279
1280         mine_transaction(&nodes[0], &remote_txn[0]);
1281         check_added_monitors!(nodes[0], 1);
1282         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1284
1285         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286         assert_eq!(claim_txn.len(), 3);
1287
1288         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289         check_spends!(claim_txn[1], remote_txn[0]);
1290         check_spends!(claim_txn[2], remote_txn[0]);
1291         let preimage_tx = &claim_txn[0];
1292         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293                 (&claim_txn[1], &claim_txn[2])
1294         } else {
1295                 (&claim_txn[2], &claim_txn[1])
1296         };
1297
1298         assert_eq!(preimage_tx.input.len(), 1);
1299         assert_eq!(preimage_bump_tx.input.len(), 1);
1300
1301         assert_eq!(preimage_tx.input.len(), 1);
1302         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1304
1305         assert_eq!(timeout_tx.input.len(), 1);
1306         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307         check_spends!(timeout_tx, remote_txn[0]);
1308         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1309
1310         let events = nodes[0].node.get_and_clear_pending_msg_events();
1311         assert_eq!(events.len(), 3);
1312         for e in events {
1313                 match e {
1314                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1318                         },
1319                         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, .. } } => {
1320                                 assert!(update_add_htlcs.is_empty());
1321                                 assert!(update_fail_htlcs.is_empty());
1322                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1323                                 assert!(update_fail_malformed_htlcs.is_empty());
1324                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1325                         },
1326                         _ => panic!("Unexpected event"),
1327                 }
1328         }
1329 }
1330
1331 #[test]
1332 fn test_basic_channel_reserve() {
1333         let chanmon_cfgs = create_chanmon_cfgs(2);
1334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1338
1339         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340         let channel_reserve = chan_stat.channel_reserve_msat;
1341
1342         // The 2* and +1 are for the fee spike reserve.
1343         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));
1344         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1346         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1347                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1348         match err {
1349                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1350                         match &fails[0] {
1351                                 &APIError::ChannelUnavailable{ref err} =>
1352                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1353                                 _ => panic!("Unexpected error variant"),
1354                         }
1355                 },
1356                 _ => panic!("Unexpected error variant"),
1357         }
1358         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1359         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1360
1361         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1362 }
1363
1364 #[test]
1365 fn test_fee_spike_violation_fails_htlc() {
1366         let chanmon_cfgs = create_chanmon_cfgs(2);
1367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1369         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1370         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1371
1372         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1373         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1374         let secp_ctx = Secp256k1::new();
1375         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1376
1377         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1378
1379         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1380         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1381                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1382         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1383         let msg = msgs::UpdateAddHTLC {
1384                 channel_id: chan.2,
1385                 htlc_id: 0,
1386                 amount_msat: htlc_msat,
1387                 payment_hash: payment_hash,
1388                 cltv_expiry: htlc_cltv,
1389                 onion_routing_packet: onion_packet,
1390         };
1391
1392         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1393
1394         // Now manually create the commitment_signed message corresponding to the update_add
1395         // nodes[0] just sent. In the code for construction of this message, "local" refers
1396         // to the sender of the message, and "remote" refers to the receiver.
1397
1398         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1399
1400         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1401
1402         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1403         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1404         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1405                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1406                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1407                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1408                 let chan_signer = local_chan.get_signer();
1409                 // Make the signer believe we validated another commitment, so we can release the secret
1410                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1411
1412                 let pubkeys = chan_signer.pubkeys();
1413                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1414                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1415                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1416                  chan_signer.pubkeys().funding_pubkey)
1417         };
1418         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1419                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1420                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1421                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422                 let chan_signer = remote_chan.get_signer();
1423                 let pubkeys = chan_signer.pubkeys();
1424                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1425                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1426                  chan_signer.pubkeys().funding_pubkey)
1427         };
1428
1429         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1430         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1431                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1432
1433         // Build the remote commitment transaction so we can sign it, and then later use the
1434         // signature for the commitment_signed message.
1435         let local_chan_balance = 1313;
1436
1437         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1438                 offered: false,
1439                 amount_msat: 3460001,
1440                 cltv_expiry: htlc_cltv,
1441                 payment_hash,
1442                 transaction_output_index: Some(1),
1443         };
1444
1445         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1446
1447         let res = {
1448                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1449                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1450                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1451                 let local_chan_signer = local_chan.get_signer();
1452                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1453                         commitment_number,
1454                         95000,
1455                         local_chan_balance,
1456                         local_chan.opt_anchors(), local_funding, remote_funding,
1457                         commit_tx_keys.clone(),
1458                         feerate_per_kw,
1459                         &mut vec![(accepted_htlc_info, ())],
1460                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1461                 );
1462                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1463         };
1464
1465         let commit_signed_msg = msgs::CommitmentSigned {
1466                 channel_id: chan.2,
1467                 signature: res.0,
1468                 htlc_signatures: res.1,
1469                 #[cfg(taproot)]
1470                 partial_signature_with_nonce: None,
1471         };
1472
1473         // Send the commitment_signed message to the nodes[1].
1474         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1475         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1476
1477         // Send the RAA to nodes[1].
1478         let raa_msg = msgs::RevokeAndACK {
1479                 channel_id: chan.2,
1480                 per_commitment_secret: local_secret,
1481                 next_per_commitment_point: next_local_point,
1482                 #[cfg(taproot)]
1483                 next_local_nonce: None,
1484         };
1485         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1486
1487         let events = nodes[1].node.get_and_clear_pending_msg_events();
1488         assert_eq!(events.len(), 1);
1489         // Make sure the HTLC failed in the way we expect.
1490         match events[0] {
1491                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1492                         assert_eq!(update_fail_htlcs.len(), 1);
1493                         update_fail_htlcs[0].clone()
1494                 },
1495                 _ => panic!("Unexpected event"),
1496         };
1497         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1498                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1499
1500         check_added_monitors!(nodes[1], 2);
1501 }
1502
1503 #[test]
1504 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1505         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1506         // Set the fee rate for the channel very high, to the point where the fundee
1507         // sending any above-dust amount would result in a channel reserve violation.
1508         // In this test we check that we would be prevented from sending an HTLC in
1509         // this situation.
1510         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1511         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1512         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1513         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1514         let default_config = UserConfig::default();
1515         let opt_anchors = false;
1516
1517         let mut push_amt = 100_000_000;
1518         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1519
1520         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1521
1522         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1523
1524         // Sending exactly enough to hit the reserve amount should be accepted
1525         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1526                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1527         }
1528
1529         // However one more HTLC should be significantly over the reserve amount and fail.
1530         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1531         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1532                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1533                 ), true, APIError::ChannelUnavailable { ref err },
1534                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1535         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1536         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);
1537 }
1538
1539 #[test]
1540 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1541         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1542         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1545         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1546         let default_config = UserConfig::default();
1547         let opt_anchors = false;
1548
1549         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1550         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1551         // transaction fee with 0 HTLCs (183 sats)).
1552         let mut push_amt = 100_000_000;
1553         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1554         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1555         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1556
1557         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1558         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1559                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1560         }
1561
1562         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1563         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1564         let secp_ctx = Secp256k1::new();
1565         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1566         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1567         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1568         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1569                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1570         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1571         let msg = msgs::UpdateAddHTLC {
1572                 channel_id: chan.2,
1573                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1574                 amount_msat: htlc_msat,
1575                 payment_hash: payment_hash,
1576                 cltv_expiry: htlc_cltv,
1577                 onion_routing_packet: onion_packet,
1578         };
1579
1580         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1581         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1582         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);
1583         assert_eq!(nodes[0].node.list_channels().len(), 0);
1584         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1585         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1586         check_added_monitors!(nodes[0], 1);
1587         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() });
1588 }
1589
1590 #[test]
1591 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1592         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1593         // calculating our commitment transaction fee (this was previously broken).
1594         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1595         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1596
1597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1599         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1600         let default_config = UserConfig::default();
1601         let opt_anchors = false;
1602
1603         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1604         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1605         // transaction fee with 0 HTLCs (183 sats)).
1606         let mut push_amt = 100_000_000;
1607         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1608         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1609         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1610
1611         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1612                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1613         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1614         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1615         // commitment transaction fee.
1616         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1617
1618         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1619         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1620                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1621         }
1622
1623         // One more than the dust amt should fail, however.
1624         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1625         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1626                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1627                 ), true, APIError::ChannelUnavailable { ref err },
1628                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1629 }
1630
1631 #[test]
1632 fn test_chan_init_feerate_unaffordability() {
1633         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1634         // channel reserve and feerate requirements.
1635         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1636         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1639         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1640         let default_config = UserConfig::default();
1641         let opt_anchors = false;
1642
1643         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1644         // HTLC.
1645         let mut push_amt = 100_000_000;
1646         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1647         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1648                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1649
1650         // During open, we don't have a "counterparty channel reserve" to check against, so that
1651         // requirement only comes into play on the open_channel handling side.
1652         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1653         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1654         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1655         open_channel_msg.push_msat += 1;
1656         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1657
1658         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1659         assert_eq!(msg_events.len(), 1);
1660         match msg_events[0] {
1661                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1662                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1663                 },
1664                 _ => panic!("Unexpected event"),
1665         }
1666 }
1667
1668 #[test]
1669 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1670         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1671         // calculating our counterparty's commitment transaction fee (this was previously broken).
1672         let chanmon_cfgs = create_chanmon_cfgs(2);
1673         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1674         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1675         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1676         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1677
1678         let payment_amt = 46000; // Dust amount
1679         // In the previous code, these first four payments would succeed.
1680         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1682         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684
1685         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1686         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691
1692         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1693         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1694         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1695         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 }
1697
1698 #[test]
1699 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1700         let chanmon_cfgs = create_chanmon_cfgs(3);
1701         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1702         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1703         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1704         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1705         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1706
1707         let feemsat = 239;
1708         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1709         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1710         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1711         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1712
1713         // Add a 2* and +1 for the fee spike reserve.
1714         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1715         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;
1716         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1717
1718         // Add a pending HTLC.
1719         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1720         let payment_event_1 = {
1721                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1722                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1723                 check_added_monitors!(nodes[0], 1);
1724
1725                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1726                 assert_eq!(events.len(), 1);
1727                 SendEvent::from_event(events.remove(0))
1728         };
1729         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1730
1731         // Attempt to trigger a channel reserve violation --> payment failure.
1732         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1733         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;
1734         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1735         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1736
1737         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1738         let secp_ctx = Secp256k1::new();
1739         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1740         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1741         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1742         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1743                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1744         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1745         let msg = msgs::UpdateAddHTLC {
1746                 channel_id: chan.2,
1747                 htlc_id: 1,
1748                 amount_msat: htlc_msat + 1,
1749                 payment_hash: our_payment_hash_1,
1750                 cltv_expiry: htlc_cltv,
1751                 onion_routing_packet: onion_packet,
1752         };
1753
1754         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1755         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1756         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1757         assert_eq!(nodes[1].node.list_channels().len(), 1);
1758         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1759         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1760         check_added_monitors!(nodes[1], 1);
1761         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1762 }
1763
1764 #[test]
1765 fn test_inbound_outbound_capacity_is_not_zero() {
1766         let chanmon_cfgs = create_chanmon_cfgs(2);
1767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1770         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1771         let channels0 = node_chanmgrs[0].list_channels();
1772         let channels1 = node_chanmgrs[1].list_channels();
1773         let default_config = UserConfig::default();
1774         assert_eq!(channels0.len(), 1);
1775         assert_eq!(channels1.len(), 1);
1776
1777         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1778         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1779         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1780
1781         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1783 }
1784
1785 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1786         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1787 }
1788
1789 #[test]
1790 fn test_channel_reserve_holding_cell_htlcs() {
1791         let chanmon_cfgs = create_chanmon_cfgs(3);
1792         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1793         // When this test was written, the default base fee floated based on the HTLC count.
1794         // It is now fixed, so we simply set the fee to the expected value here.
1795         let mut config = test_default_channel_config();
1796         config.channel_config.forwarding_fee_base_msat = 239;
1797         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1798         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1799         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1800         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1801
1802         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1803         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1804
1805         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1806         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1807
1808         macro_rules! expect_forward {
1809                 ($node: expr) => {{
1810                         let mut events = $node.node.get_and_clear_pending_msg_events();
1811                         assert_eq!(events.len(), 1);
1812                         check_added_monitors!($node, 1);
1813                         let payment_event = SendEvent::from_event(events.remove(0));
1814                         payment_event
1815                 }}
1816         }
1817
1818         let feemsat = 239; // set above
1819         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1820         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1821         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1822
1823         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1824
1825         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1826         {
1827                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1828                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1829                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1830                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1831                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1832
1833                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1834                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1835                         ), true, APIError::ChannelUnavailable { ref err },
1836                         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)));
1837                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1838                 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);
1839         }
1840
1841         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1842         // nodes[0]'s wealth
1843         loop {
1844                 let amt_msat = recv_value_0 + total_fee_msat;
1845                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1846                 // Also, ensure that each payment has enough to be over the dust limit to
1847                 // ensure it'll be included in each commit tx fee calculation.
1848                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1849                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1850                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1851                         break;
1852                 }
1853
1854                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1855                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1856                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1857                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1858                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1859
1860                 let (stat01_, stat11_, stat12_, stat22_) = (
1861                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1862                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1863                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1864                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1865                 );
1866
1867                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1868                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1869                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1870                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1871                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1872         }
1873
1874         // adding pending output.
1875         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1876         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1877         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1878         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1879         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1880         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1881         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1882         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1883         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1884         // policy.
1885         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1886         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1887         let amt_msat_1 = recv_value_1 + total_fee_msat;
1888
1889         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);
1890         let payment_event_1 = {
1891                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1892                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1893                 check_added_monitors!(nodes[0], 1);
1894
1895                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1896                 assert_eq!(events.len(), 1);
1897                 SendEvent::from_event(events.remove(0))
1898         };
1899         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1900
1901         // channel reserve test with htlc pending output > 0
1902         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1903         {
1904                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1905                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1906                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1907                         ), true, APIError::ChannelUnavailable { ref err },
1908                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1909                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1910         }
1911
1912         // split the rest to test holding cell
1913         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1914         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1915         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1916         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1917         {
1918                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1919                 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);
1920         }
1921
1922         // now see if they go through on both sides
1923         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);
1924         // but this will stuck in the holding cell
1925         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1926                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1927         check_added_monitors!(nodes[0], 0);
1928         let events = nodes[0].node.get_and_clear_pending_events();
1929         assert_eq!(events.len(), 0);
1930
1931         // test with outbound holding cell amount > 0
1932         {
1933                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1934                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1935                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1936                         ), true, APIError::ChannelUnavailable { ref err },
1937                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1938                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1939                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1940         }
1941
1942         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);
1943         // this will also stuck in the holding cell
1944         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1945                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1946         check_added_monitors!(nodes[0], 0);
1947         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1948         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1949
1950         // flush the pending htlc
1951         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1952         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1953         check_added_monitors!(nodes[1], 1);
1954
1955         // the pending htlc should be promoted to committed
1956         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1957         check_added_monitors!(nodes[0], 1);
1958         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1959
1960         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1961         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1962         // No commitment_signed so get_event_msg's assert(len == 1) passes
1963         check_added_monitors!(nodes[0], 1);
1964
1965         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1966         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1967         check_added_monitors!(nodes[1], 1);
1968
1969         expect_pending_htlcs_forwardable!(nodes[1]);
1970
1971         let ref payment_event_11 = expect_forward!(nodes[1]);
1972         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1973         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1974
1975         expect_pending_htlcs_forwardable!(nodes[2]);
1976         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1977
1978         // flush the htlcs in the holding cell
1979         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1980         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1981         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1982         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1983         expect_pending_htlcs_forwardable!(nodes[1]);
1984
1985         let ref payment_event_3 = expect_forward!(nodes[1]);
1986         assert_eq!(payment_event_3.msgs.len(), 2);
1987         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1988         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1989
1990         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1991         expect_pending_htlcs_forwardable!(nodes[2]);
1992
1993         let events = nodes[2].node.get_and_clear_pending_events();
1994         assert_eq!(events.len(), 2);
1995         match events[0] {
1996                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1997                         assert_eq!(our_payment_hash_21, *payment_hash);
1998                         assert_eq!(recv_value_21, amount_msat);
1999                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2000                         assert_eq!(via_channel_id, Some(chan_2.2));
2001                         match &purpose {
2002                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2003                                         assert!(payment_preimage.is_none());
2004                                         assert_eq!(our_payment_secret_21, *payment_secret);
2005                                 },
2006                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2007                         }
2008                 },
2009                 _ => panic!("Unexpected event"),
2010         }
2011         match events[1] {
2012                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2013                         assert_eq!(our_payment_hash_22, *payment_hash);
2014                         assert_eq!(recv_value_22, amount_msat);
2015                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2016                         assert_eq!(via_channel_id, Some(chan_2.2));
2017                         match &purpose {
2018                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2019                                         assert!(payment_preimage.is_none());
2020                                         assert_eq!(our_payment_secret_22, *payment_secret);
2021                                 },
2022                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2023                         }
2024                 },
2025                 _ => panic!("Unexpected event"),
2026         }
2027
2028         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2029         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2030         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2031
2032         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2033         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2034         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2035
2036         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2037         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);
2038         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2039         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2040         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2041
2042         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2043         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2044 }
2045
2046 #[test]
2047 fn channel_reserve_in_flight_removes() {
2048         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2049         // can send to its counterparty, but due to update ordering, the other side may not yet have
2050         // considered those HTLCs fully removed.
2051         // This tests that we don't count HTLCs which will not be included in the next remote
2052         // commitment transaction towards the reserve value (as it implies no commitment transaction
2053         // will be generated which violates the remote reserve value).
2054         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2055         // To test this we:
2056         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2057         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2058         //    you only consider the value of the first HTLC, it may not),
2059         //  * start routing a third HTLC from A to B,
2060         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2061         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2062         //  * deliver the first fulfill from B
2063         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2064         //    claim,
2065         //  * deliver A's response CS and RAA.
2066         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2067         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2068         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2069         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2070         let chanmon_cfgs = create_chanmon_cfgs(2);
2071         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2072         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2073         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2074         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2075
2076         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2077         // Route the first two HTLCs.
2078         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2079         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2080         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2081
2082         // Start routing the third HTLC (this is just used to get everyone in the right state).
2083         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2084         let send_1 = {
2085                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2086                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2087                 check_added_monitors!(nodes[0], 1);
2088                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2089                 assert_eq!(events.len(), 1);
2090                 SendEvent::from_event(events.remove(0))
2091         };
2092
2093         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2094         // initial fulfill/CS.
2095         nodes[1].node.claim_funds(payment_preimage_1);
2096         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2097         check_added_monitors!(nodes[1], 1);
2098         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2099
2100         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2101         // remove the second HTLC when we send the HTLC back from B to A.
2102         nodes[1].node.claim_funds(payment_preimage_2);
2103         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2104         check_added_monitors!(nodes[1], 1);
2105         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2106
2107         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2108         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2109         check_added_monitors!(nodes[0], 1);
2110         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2111         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2112
2113         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2114         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2115         check_added_monitors!(nodes[1], 1);
2116         // B is already AwaitingRAA, so cant generate a CS here
2117         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2118
2119         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2120         check_added_monitors!(nodes[1], 1);
2121         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2122
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         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2126
2127         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2128         check_added_monitors!(nodes[1], 1);
2129         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2130
2131         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2132         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2133         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2134         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2135         // on-chain as necessary).
2136         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2137         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2138         check_added_monitors!(nodes[0], 1);
2139         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2140         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2141
2142         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2143         check_added_monitors!(nodes[1], 1);
2144         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2145
2146         expect_pending_htlcs_forwardable!(nodes[1]);
2147         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2148
2149         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2150         // resolve the second HTLC from A's point of view.
2151         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2152         check_added_monitors!(nodes[0], 1);
2153         expect_payment_path_successful!(nodes[0]);
2154         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2155
2156         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2157         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2158         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2159         let send_2 = {
2160                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2161                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2162                 check_added_monitors!(nodes[1], 1);
2163                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2164                 assert_eq!(events.len(), 1);
2165                 SendEvent::from_event(events.remove(0))
2166         };
2167
2168         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2169         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2170         check_added_monitors!(nodes[0], 1);
2171         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2172
2173         // Now just resolve all the outstanding messages/HTLCs for completeness...
2174
2175         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2176         check_added_monitors!(nodes[1], 1);
2177         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2178
2179         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2180         check_added_monitors!(nodes[1], 1);
2181
2182         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2183         check_added_monitors!(nodes[0], 1);
2184         expect_payment_path_successful!(nodes[0]);
2185         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2186
2187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2188         check_added_monitors!(nodes[1], 1);
2189         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2190
2191         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2192         check_added_monitors!(nodes[0], 1);
2193
2194         expect_pending_htlcs_forwardable!(nodes[0]);
2195         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2196
2197         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2198         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2199 }
2200
2201 #[test]
2202 fn channel_monitor_network_test() {
2203         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2204         // tests that ChannelMonitor is able to recover from various states.
2205         let chanmon_cfgs = create_chanmon_cfgs(5);
2206         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2207         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2208         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2209
2210         // Create some initial channels
2211         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2212         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2213         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2214         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2215
2216         // Make sure all nodes are at the same starting height
2217         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2218         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2219         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2220         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2221         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2222
2223         // Rebalance the network a bit by relaying one payment through all the channels...
2224         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2225         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2226         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2227         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2228
2229         // Simple case with no pending HTLCs:
2230         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2231         check_added_monitors!(nodes[1], 1);
2232         check_closed_broadcast!(nodes[1], true);
2233         {
2234                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2235                 assert_eq!(node_txn.len(), 1);
2236                 mine_transaction(&nodes[0], &node_txn[0]);
2237                 check_added_monitors!(nodes[0], 1);
2238                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2239         }
2240         check_closed_broadcast!(nodes[0], true);
2241         assert_eq!(nodes[0].node.list_channels().len(), 0);
2242         assert_eq!(nodes[1].node.list_channels().len(), 1);
2243         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2244         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2245
2246         // One pending HTLC is discarded by the force-close:
2247         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2248
2249         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2250         // broadcasted until we reach the timelock time).
2251         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2252         check_closed_broadcast!(nodes[1], true);
2253         check_added_monitors!(nodes[1], 1);
2254         {
2255                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2256                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2257                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2258                 mine_transaction(&nodes[2], &node_txn[0]);
2259                 check_added_monitors!(nodes[2], 1);
2260                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2261         }
2262         check_closed_broadcast!(nodes[2], true);
2263         assert_eq!(nodes[1].node.list_channels().len(), 0);
2264         assert_eq!(nodes[2].node.list_channels().len(), 1);
2265         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2266         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2267
2268         macro_rules! claim_funds {
2269                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2270                         {
2271                                 $node.node.claim_funds($preimage);
2272                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2273                                 check_added_monitors!($node, 1);
2274
2275                                 let events = $node.node.get_and_clear_pending_msg_events();
2276                                 assert_eq!(events.len(), 1);
2277                                 match events[0] {
2278                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2279                                                 assert!(update_add_htlcs.is_empty());
2280                                                 assert!(update_fail_htlcs.is_empty());
2281                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2282                                         },
2283                                         _ => panic!("Unexpected event"),
2284                                 };
2285                         }
2286                 }
2287         }
2288
2289         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2290         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2291         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2292         check_added_monitors!(nodes[2], 1);
2293         check_closed_broadcast!(nodes[2], true);
2294         let node2_commitment_txid;
2295         {
2296                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2297                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2298                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2299                 node2_commitment_txid = node_txn[0].txid();
2300
2301                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2302                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2303                 mine_transaction(&nodes[3], &node_txn[0]);
2304                 check_added_monitors!(nodes[3], 1);
2305                 check_preimage_claim(&nodes[3], &node_txn);
2306         }
2307         check_closed_broadcast!(nodes[3], true);
2308         assert_eq!(nodes[2].node.list_channels().len(), 0);
2309         assert_eq!(nodes[3].node.list_channels().len(), 1);
2310         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2311         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2312
2313         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2314         // confusing us in the following tests.
2315         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2316
2317         // One pending HTLC to time out:
2318         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2319         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2320         // buffer space).
2321
2322         let (close_chan_update_1, close_chan_update_2) = {
2323                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2324                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2325                 assert_eq!(events.len(), 2);
2326                 let close_chan_update_1 = match events[0] {
2327                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2328                                 msg.clone()
2329                         },
2330                         _ => panic!("Unexpected event"),
2331                 };
2332                 match events[1] {
2333                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2335                         },
2336                         _ => panic!("Unexpected event"),
2337                 }
2338                 check_added_monitors!(nodes[3], 1);
2339
2340                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2341                 {
2342                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2343                         node_txn.retain(|tx| {
2344                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2345                                         false
2346                                 } else { true }
2347                         });
2348                 }
2349
2350                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2351
2352                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2353                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2354
2355                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2356                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2357                 assert_eq!(events.len(), 2);
2358                 let close_chan_update_2 = match events[0] {
2359                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2360                                 msg.clone()
2361                         },
2362                         _ => panic!("Unexpected event"),
2363                 };
2364                 match events[1] {
2365                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2366                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2367                         },
2368                         _ => panic!("Unexpected event"),
2369                 }
2370                 check_added_monitors!(nodes[4], 1);
2371                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2372
2373                 mine_transaction(&nodes[4], &node_txn[0]);
2374                 check_preimage_claim(&nodes[4], &node_txn);
2375                 (close_chan_update_1, close_chan_update_2)
2376         };
2377         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2378         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2379         assert_eq!(nodes[3].node.list_channels().len(), 0);
2380         assert_eq!(nodes[4].node.list_channels().len(), 0);
2381
2382         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2383                 ChannelMonitorUpdateStatus::Completed);
2384         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2385         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2386 }
2387
2388 #[test]
2389 fn test_justice_tx_htlc_timeout() {
2390         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2391         let mut alice_config = UserConfig::default();
2392         alice_config.channel_handshake_config.announced_channel = true;
2393         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2394         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2395         let mut bob_config = UserConfig::default();
2396         bob_config.channel_handshake_config.announced_channel = true;
2397         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2398         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2399         let user_cfgs = [Some(alice_config), Some(bob_config)];
2400         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2401         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2402         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2403         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2404         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2405         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2406         // Create some new channels:
2407         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2408
2409         // A pending HTLC which will be revoked:
2410         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2411         // Get the will-be-revoked local txn from nodes[0]
2412         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2413         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2414         assert_eq!(revoked_local_txn[0].input.len(), 1);
2415         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2416         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2417         assert_eq!(revoked_local_txn[1].input.len(), 1);
2418         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2419         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2420         // Revoke the old state
2421         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2422
2423         {
2424                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2425                 {
2426                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2427                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2428                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2429                         check_spends!(node_txn[0], revoked_local_txn[0]);
2430                         node_txn.swap_remove(0);
2431                 }
2432                 check_added_monitors!(nodes[1], 1);
2433                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2434                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2435
2436                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2437                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2438                 // Verify broadcast of revoked HTLC-timeout
2439                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2440                 check_added_monitors!(nodes[0], 1);
2441                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2442                 // Broadcast revoked HTLC-timeout on node 1
2443                 mine_transaction(&nodes[1], &node_txn[1]);
2444                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2445         }
2446         get_announce_close_broadcast_events(&nodes, 0, 1);
2447         assert_eq!(nodes[0].node.list_channels().len(), 0);
2448         assert_eq!(nodes[1].node.list_channels().len(), 0);
2449 }
2450
2451 #[test]
2452 fn test_justice_tx_htlc_success() {
2453         // Test justice txn built on revoked HTLC-Success tx, against both sides
2454         let mut alice_config = UserConfig::default();
2455         alice_config.channel_handshake_config.announced_channel = true;
2456         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2457         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2458         let mut bob_config = UserConfig::default();
2459         bob_config.channel_handshake_config.announced_channel = true;
2460         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2461         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2462         let user_cfgs = [Some(alice_config), Some(bob_config)];
2463         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2464         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2465         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2468         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2469         // Create some new channels:
2470         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2471
2472         // A pending HTLC which will be revoked:
2473         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2474         // Get the will-be-revoked local txn from B
2475         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2476         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2477         assert_eq!(revoked_local_txn[0].input.len(), 1);
2478         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2479         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2480         // Revoke the old state
2481         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2482         {
2483                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2484                 {
2485                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2486                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2487                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2488
2489                         check_spends!(node_txn[0], revoked_local_txn[0]);
2490                         node_txn.swap_remove(0);
2491                 }
2492                 check_added_monitors!(nodes[0], 1);
2493                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2494
2495                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2496                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2497                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2498                 check_added_monitors!(nodes[1], 1);
2499                 mine_transaction(&nodes[0], &node_txn[1]);
2500                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2501                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2502         }
2503         get_announce_close_broadcast_events(&nodes, 0, 1);
2504         assert_eq!(nodes[0].node.list_channels().len(), 0);
2505         assert_eq!(nodes[1].node.list_channels().len(), 0);
2506 }
2507
2508 #[test]
2509 fn revoked_output_claim() {
2510         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2511         // transaction is broadcast by its counterparty
2512         let chanmon_cfgs = create_chanmon_cfgs(2);
2513         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2514         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2515         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2516         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2517         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2518         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2519         assert_eq!(revoked_local_txn.len(), 1);
2520         // Only output is the full channel value back to nodes[0]:
2521         assert_eq!(revoked_local_txn[0].output.len(), 1);
2522         // Send a payment through, updating everyone's latest commitment txn
2523         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2524
2525         // Inform nodes[1] that nodes[0] broadcast a stale tx
2526         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2527         check_added_monitors!(nodes[1], 1);
2528         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2529         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2530         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2531
2532         check_spends!(node_txn[0], revoked_local_txn[0]);
2533
2534         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2535         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2536         get_announce_close_broadcast_events(&nodes, 0, 1);
2537         check_added_monitors!(nodes[0], 1);
2538         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2539 }
2540
2541 #[test]
2542 fn claim_htlc_outputs_shared_tx() {
2543         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2544         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2545         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2548         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2549
2550         // Create some new channel:
2551         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2552
2553         // Rebalance the network to generate htlc in the two directions
2554         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2555         // 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
2556         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2557         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2558
2559         // Get the will-be-revoked local txn from node[0]
2560         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2561         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2562         assert_eq!(revoked_local_txn[0].input.len(), 1);
2563         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2564         assert_eq!(revoked_local_txn[1].input.len(), 1);
2565         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2566         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2567         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2568
2569         //Revoke the old state
2570         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2571
2572         {
2573                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2574                 check_added_monitors!(nodes[0], 1);
2575                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2576                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2577                 check_added_monitors!(nodes[1], 1);
2578                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2579                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2580                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2581
2582                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2583                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2584
2585                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2586                 check_spends!(node_txn[0], revoked_local_txn[0]);
2587
2588                 let mut witness_lens = BTreeSet::new();
2589                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2590                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2591                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2592                 assert_eq!(witness_lens.len(), 3);
2593                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2594                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2595                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2596
2597                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2598                 // ANTI_REORG_DELAY confirmations.
2599                 mine_transaction(&nodes[1], &node_txn[0]);
2600                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2601                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2602         }
2603         get_announce_close_broadcast_events(&nodes, 0, 1);
2604         assert_eq!(nodes[0].node.list_channels().len(), 0);
2605         assert_eq!(nodes[1].node.list_channels().len(), 0);
2606 }
2607
2608 #[test]
2609 fn claim_htlc_outputs_single_tx() {
2610         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2611         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2612         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2615         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2616
2617         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2618
2619         // Rebalance the network to generate htlc in the two directions
2620         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2621         // 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
2622         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2623         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2624         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2625
2626         // Get the will-be-revoked local txn from node[0]
2627         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2628
2629         //Revoke the old state
2630         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2631
2632         {
2633                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2634                 check_added_monitors!(nodes[0], 1);
2635                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2636                 check_added_monitors!(nodes[1], 1);
2637                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2638                 let mut events = nodes[0].node.get_and_clear_pending_events();
2639                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2640                 match events.last().unwrap() {
2641                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2642                         _ => panic!("Unexpected event"),
2643                 }
2644
2645                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2646                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2647
2648                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2649
2650                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2651                 assert_eq!(node_txn[0].input.len(), 1);
2652                 check_spends!(node_txn[0], chan_1.3);
2653                 assert_eq!(node_txn[1].input.len(), 1);
2654                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2655                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2656                 check_spends!(node_txn[1], node_txn[0]);
2657
2658                 // Filter out any non justice transactions.
2659                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2660                 assert!(node_txn.len() > 3);
2661
2662                 assert_eq!(node_txn[0].input.len(), 1);
2663                 assert_eq!(node_txn[1].input.len(), 1);
2664                 assert_eq!(node_txn[2].input.len(), 1);
2665
2666                 check_spends!(node_txn[0], revoked_local_txn[0]);
2667                 check_spends!(node_txn[1], revoked_local_txn[0]);
2668                 check_spends!(node_txn[2], revoked_local_txn[0]);
2669
2670                 let mut witness_lens = BTreeSet::new();
2671                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2672                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2673                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2674                 assert_eq!(witness_lens.len(), 3);
2675                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2676                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2677                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2678
2679                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2680                 // ANTI_REORG_DELAY confirmations.
2681                 mine_transaction(&nodes[1], &node_txn[0]);
2682                 mine_transaction(&nodes[1], &node_txn[1]);
2683                 mine_transaction(&nodes[1], &node_txn[2]);
2684                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2685                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2686         }
2687         get_announce_close_broadcast_events(&nodes, 0, 1);
2688         assert_eq!(nodes[0].node.list_channels().len(), 0);
2689         assert_eq!(nodes[1].node.list_channels().len(), 0);
2690 }
2691
2692 #[test]
2693 fn test_htlc_on_chain_success() {
2694         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2695         // the preimage backward accordingly. So here we test that ChannelManager is
2696         // broadcasting the right event to other nodes in payment path.
2697         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2698         // A --------------------> B ----------------------> C (preimage)
2699         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2700         // commitment transaction was broadcast.
2701         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2702         // towards B.
2703         // B should be able to claim via preimage if A then broadcasts its local tx.
2704         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2705         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2706         // PaymentSent event).
2707
2708         let chanmon_cfgs = create_chanmon_cfgs(3);
2709         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2710         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2711         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2712
2713         // Create some initial channels
2714         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2715         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2716
2717         // Ensure all nodes are at the same height
2718         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2719         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2720         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2721         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2722
2723         // Rebalance the network a bit by relaying one payment through all the channels...
2724         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2725         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2726
2727         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2728         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2729
2730         // Broadcast legit commitment tx from C on B's chain
2731         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2732         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2733         assert_eq!(commitment_tx.len(), 1);
2734         check_spends!(commitment_tx[0], chan_2.3);
2735         nodes[2].node.claim_funds(our_payment_preimage);
2736         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2737         nodes[2].node.claim_funds(our_payment_preimage_2);
2738         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2739         check_added_monitors!(nodes[2], 2);
2740         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2741         assert!(updates.update_add_htlcs.is_empty());
2742         assert!(updates.update_fail_htlcs.is_empty());
2743         assert!(updates.update_fail_malformed_htlcs.is_empty());
2744         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2745
2746         mine_transaction(&nodes[2], &commitment_tx[0]);
2747         check_closed_broadcast!(nodes[2], true);
2748         check_added_monitors!(nodes[2], 1);
2749         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2750         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2751         assert_eq!(node_txn.len(), 2);
2752         check_spends!(node_txn[0], commitment_tx[0]);
2753         check_spends!(node_txn[1], commitment_tx[0]);
2754         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2755         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2756         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2757         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2758         assert_eq!(node_txn[0].lock_time.0, 0);
2759         assert_eq!(node_txn[1].lock_time.0, 0);
2760
2761         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2762         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2763         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2764         {
2765                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2766                 assert_eq!(added_monitors.len(), 1);
2767                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2768                 added_monitors.clear();
2769         }
2770         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2771         assert_eq!(forwarded_events.len(), 3);
2772         match forwarded_events[0] {
2773                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2774                 _ => panic!("Unexpected event"),
2775         }
2776         let chan_id = Some(chan_1.2);
2777         match forwarded_events[1] {
2778                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2779                         assert_eq!(fee_earned_msat, Some(1000));
2780                         assert_eq!(prev_channel_id, chan_id);
2781                         assert_eq!(claim_from_onchain_tx, true);
2782                         assert_eq!(next_channel_id, Some(chan_2.2));
2783                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2784                 },
2785                 _ => panic!()
2786         }
2787         match forwarded_events[2] {
2788                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2789                         assert_eq!(fee_earned_msat, Some(1000));
2790                         assert_eq!(prev_channel_id, chan_id);
2791                         assert_eq!(claim_from_onchain_tx, true);
2792                         assert_eq!(next_channel_id, Some(chan_2.2));
2793                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2794                 },
2795                 _ => panic!()
2796         }
2797         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2798         {
2799                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2800                 assert_eq!(added_monitors.len(), 2);
2801                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2802                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2803                 added_monitors.clear();
2804         }
2805         assert_eq!(events.len(), 3);
2806
2807         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2808         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2809
2810         match nodes_2_event {
2811                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2812                 _ => panic!("Unexpected event"),
2813         }
2814
2815         match nodes_0_event {
2816                 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, .. } } => {
2817                         assert!(update_add_htlcs.is_empty());
2818                         assert!(update_fail_htlcs.is_empty());
2819                         assert_eq!(update_fulfill_htlcs.len(), 1);
2820                         assert!(update_fail_malformed_htlcs.is_empty());
2821                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2822                 },
2823                 _ => panic!("Unexpected event"),
2824         };
2825
2826         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2827         match events[0] {
2828                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2829                 _ => panic!("Unexpected event"),
2830         }
2831
2832         macro_rules! check_tx_local_broadcast {
2833                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2834                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2835                         assert_eq!(node_txn.len(), 2);
2836                         // Node[1]: 2 * HTLC-timeout tx
2837                         // Node[0]: 2 * HTLC-timeout tx
2838                         check_spends!(node_txn[0], $commitment_tx);
2839                         check_spends!(node_txn[1], $commitment_tx);
2840                         assert_ne!(node_txn[0].lock_time.0, 0);
2841                         assert_ne!(node_txn[1].lock_time.0, 0);
2842                         if $htlc_offered {
2843                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2846                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2847                         } else {
2848                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2849                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2850                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2851                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2852                         }
2853                         node_txn.clear();
2854                 } }
2855         }
2856         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2857         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2858
2859         // Broadcast legit commitment tx from A on B's chain
2860         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2861         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2862         check_spends!(node_a_commitment_tx[0], chan_1.3);
2863         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2864         check_closed_broadcast!(nodes[1], true);
2865         check_added_monitors!(nodes[1], 1);
2866         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2867         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2868         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2869         let commitment_spend =
2870                 if node_txn.len() == 1 {
2871                         &node_txn[0]
2872                 } else {
2873                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2874                         // FullBlockViaListen
2875                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2876                                 check_spends!(node_txn[1], commitment_tx[0]);
2877                                 check_spends!(node_txn[2], commitment_tx[0]);
2878                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2879                                 &node_txn[0]
2880                         } else {
2881                                 check_spends!(node_txn[0], commitment_tx[0]);
2882                                 check_spends!(node_txn[1], commitment_tx[0]);
2883                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2884                                 &node_txn[2]
2885                         }
2886                 };
2887
2888         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2889         assert_eq!(commitment_spend.input.len(), 2);
2890         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2891         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2892         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2893         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2894         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2895         // we already checked the same situation with A.
2896
2897         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2898         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2899         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2900         check_closed_broadcast!(nodes[0], true);
2901         check_added_monitors!(nodes[0], 1);
2902         let events = nodes[0].node.get_and_clear_pending_events();
2903         assert_eq!(events.len(), 5);
2904         let mut first_claimed = false;
2905         for event in events {
2906                 match event {
2907                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2908                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2909                                         assert!(!first_claimed);
2910                                         first_claimed = true;
2911                                 } else {
2912                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2913                                         assert_eq!(payment_hash, payment_hash_2);
2914                                 }
2915                         },
2916                         Event::PaymentPathSuccessful { .. } => {},
2917                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2918                         _ => panic!("Unexpected event"),
2919                 }
2920         }
2921         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2922 }
2923
2924 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2925         // Test that in case of a unilateral close onchain, we detect the state of output and
2926         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2927         // broadcasting the right event to other nodes in payment path.
2928         // A ------------------> B ----------------------> C (timeout)
2929         //    B's commitment tx                 C's commitment tx
2930         //            \                                  \
2931         //         B's HTLC timeout tx               B's timeout tx
2932
2933         let chanmon_cfgs = create_chanmon_cfgs(3);
2934         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2935         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2936         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2937         *nodes[0].connect_style.borrow_mut() = connect_style;
2938         *nodes[1].connect_style.borrow_mut() = connect_style;
2939         *nodes[2].connect_style.borrow_mut() = connect_style;
2940
2941         // Create some intial channels
2942         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2943         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2944
2945         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2946         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2947         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2948
2949         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2950
2951         // Broadcast legit commitment tx from C on B's chain
2952         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2953         check_spends!(commitment_tx[0], chan_2.3);
2954         nodes[2].node.fail_htlc_backwards(&payment_hash);
2955         check_added_monitors!(nodes[2], 0);
2956         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2957         check_added_monitors!(nodes[2], 1);
2958
2959         let events = nodes[2].node.get_and_clear_pending_msg_events();
2960         assert_eq!(events.len(), 1);
2961         match events[0] {
2962                 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, .. } } => {
2963                         assert!(update_add_htlcs.is_empty());
2964                         assert!(!update_fail_htlcs.is_empty());
2965                         assert!(update_fulfill_htlcs.is_empty());
2966                         assert!(update_fail_malformed_htlcs.is_empty());
2967                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2968                 },
2969                 _ => panic!("Unexpected event"),
2970         };
2971         mine_transaction(&nodes[2], &commitment_tx[0]);
2972         check_closed_broadcast!(nodes[2], true);
2973         check_added_monitors!(nodes[2], 1);
2974         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2975         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2976         assert_eq!(node_txn.len(), 0);
2977
2978         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2979         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2980         mine_transaction(&nodes[1], &commitment_tx[0]);
2981         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2982         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2983         let timeout_tx = {
2984                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2985                 if nodes[1].connect_style.borrow().skips_blocks() {
2986                         assert_eq!(txn.len(), 1);
2987                 } else {
2988                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2989                 }
2990                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2991                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2992                 txn.remove(0)
2993         };
2994
2995         mine_transaction(&nodes[1], &timeout_tx);
2996         check_added_monitors!(nodes[1], 1);
2997         check_closed_broadcast!(nodes[1], true);
2998
2999         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3000
3001         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 }]);
3002         check_added_monitors!(nodes[1], 1);
3003         let events = nodes[1].node.get_and_clear_pending_msg_events();
3004         assert_eq!(events.len(), 1);
3005         match events[0] {
3006                 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, .. } } => {
3007                         assert!(update_add_htlcs.is_empty());
3008                         assert!(!update_fail_htlcs.is_empty());
3009                         assert!(update_fulfill_htlcs.is_empty());
3010                         assert!(update_fail_malformed_htlcs.is_empty());
3011                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3012                 },
3013                 _ => panic!("Unexpected event"),
3014         };
3015
3016         // Broadcast legit commitment tx from B on A's chain
3017         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3018         check_spends!(commitment_tx[0], chan_1.3);
3019
3020         mine_transaction(&nodes[0], &commitment_tx[0]);
3021         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3022
3023         check_closed_broadcast!(nodes[0], true);
3024         check_added_monitors!(nodes[0], 1);
3025         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3026         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3027         assert_eq!(node_txn.len(), 1);
3028         check_spends!(node_txn[0], commitment_tx[0]);
3029         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3030 }
3031
3032 #[test]
3033 fn test_htlc_on_chain_timeout() {
3034         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3035         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3036         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3037 }
3038
3039 #[test]
3040 fn test_simple_commitment_revoked_fail_backward() {
3041         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3042         // and fail backward accordingly.
3043
3044         let chanmon_cfgs = create_chanmon_cfgs(3);
3045         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3046         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3047         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3048
3049         // Create some initial channels
3050         create_announced_chan_between_nodes(&nodes, 0, 1);
3051         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3052
3053         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3054         // Get the will-be-revoked local txn from nodes[2]
3055         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3056         // Revoke the old state
3057         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3058
3059         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3060
3061         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3062         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3063         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3064         check_added_monitors!(nodes[1], 1);
3065         check_closed_broadcast!(nodes[1], true);
3066
3067         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 }]);
3068         check_added_monitors!(nodes[1], 1);
3069         let events = nodes[1].node.get_and_clear_pending_msg_events();
3070         assert_eq!(events.len(), 1);
3071         match events[0] {
3072                 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, .. } } => {
3073                         assert!(update_add_htlcs.is_empty());
3074                         assert_eq!(update_fail_htlcs.len(), 1);
3075                         assert!(update_fulfill_htlcs.is_empty());
3076                         assert!(update_fail_malformed_htlcs.is_empty());
3077                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3078
3079                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3080                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3081                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3082                 },
3083                 _ => panic!("Unexpected event"),
3084         }
3085 }
3086
3087 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3088         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3089         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3090         // commitment transaction anymore.
3091         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3092         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3093         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3094         // technically disallowed and we should probably handle it reasonably.
3095         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3096         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3097         // transactions:
3098         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3099         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3100         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3101         //   and once they revoke the previous commitment transaction (allowing us to send a new
3102         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3103         let chanmon_cfgs = create_chanmon_cfgs(3);
3104         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3105         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3106         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3107
3108         // Create some initial channels
3109         create_announced_chan_between_nodes(&nodes, 0, 1);
3110         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3111
3112         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 });
3113         // Get the will-be-revoked local txn from nodes[2]
3114         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3115         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3116         // Revoke the old state
3117         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3118
3119         let value = if use_dust {
3120                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3121                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3122                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3123                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3124         } else { 3000000 };
3125
3126         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3127         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3128         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3129
3130         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3131         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3132         check_added_monitors!(nodes[2], 1);
3133         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3134         assert!(updates.update_add_htlcs.is_empty());
3135         assert!(updates.update_fulfill_htlcs.is_empty());
3136         assert!(updates.update_fail_malformed_htlcs.is_empty());
3137         assert_eq!(updates.update_fail_htlcs.len(), 1);
3138         assert!(updates.update_fee.is_none());
3139         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3140         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3141         // Drop the last RAA from 3 -> 2
3142
3143         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3144         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3145         check_added_monitors!(nodes[2], 1);
3146         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3147         assert!(updates.update_add_htlcs.is_empty());
3148         assert!(updates.update_fulfill_htlcs.is_empty());
3149         assert!(updates.update_fail_malformed_htlcs.is_empty());
3150         assert_eq!(updates.update_fail_htlcs.len(), 1);
3151         assert!(updates.update_fee.is_none());
3152         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3153         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3154         check_added_monitors!(nodes[1], 1);
3155         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3156         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3157         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3158         check_added_monitors!(nodes[2], 1);
3159
3160         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3161         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3162         check_added_monitors!(nodes[2], 1);
3163         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3164         assert!(updates.update_add_htlcs.is_empty());
3165         assert!(updates.update_fulfill_htlcs.is_empty());
3166         assert!(updates.update_fail_malformed_htlcs.is_empty());
3167         assert_eq!(updates.update_fail_htlcs.len(), 1);
3168         assert!(updates.update_fee.is_none());
3169         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3170         // At this point first_payment_hash has dropped out of the latest two commitment
3171         // transactions that nodes[1] is tracking...
3172         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3173         check_added_monitors!(nodes[1], 1);
3174         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3175         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3176         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3177         check_added_monitors!(nodes[2], 1);
3178
3179         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3180         // on nodes[2]'s RAA.
3181         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3182         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3183                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3184         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3185         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3186         check_added_monitors!(nodes[1], 0);
3187
3188         if deliver_bs_raa {
3189                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3190                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3191                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3192                 check_added_monitors!(nodes[1], 1);
3193                 let events = nodes[1].node.get_and_clear_pending_events();
3194                 assert_eq!(events.len(), 2);
3195                 match events[0] {
3196                         Event::PendingHTLCsForwardable { .. } => { },
3197                         _ => panic!("Unexpected event"),
3198                 };
3199                 match events[1] {
3200                         Event::HTLCHandlingFailed { .. } => { },
3201                         _ => panic!("Unexpected event"),
3202                 }
3203                 // Deliberately don't process the pending fail-back so they all fail back at once after
3204                 // block connection just like the !deliver_bs_raa case
3205         }
3206
3207         let mut failed_htlcs = HashSet::new();
3208         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3209
3210         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3211         check_added_monitors!(nodes[1], 1);
3212         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3213
3214         let events = nodes[1].node.get_and_clear_pending_events();
3215         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3216         match events[0] {
3217                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3218                 _ => panic!("Unexepected event"),
3219         }
3220         match events[1] {
3221                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3222                         assert_eq!(*payment_hash, fourth_payment_hash);
3223                 },
3224                 _ => panic!("Unexpected event"),
3225         }
3226         match events[2] {
3227                 Event::PaymentFailed { ref payment_hash, .. } => {
3228                         assert_eq!(*payment_hash, fourth_payment_hash);
3229                 },
3230                 _ => panic!("Unexpected event"),
3231         }
3232
3233         nodes[1].node.process_pending_htlc_forwards();
3234         check_added_monitors!(nodes[1], 1);
3235
3236         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3237         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3238
3239         if deliver_bs_raa {
3240                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3241                 match nodes_2_event {
3242                         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, .. } } => {
3243                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3244                                 assert_eq!(update_add_htlcs.len(), 1);
3245                                 assert!(update_fulfill_htlcs.is_empty());
3246                                 assert!(update_fail_htlcs.is_empty());
3247                                 assert!(update_fail_malformed_htlcs.is_empty());
3248                         },
3249                         _ => panic!("Unexpected event"),
3250                 }
3251         }
3252
3253         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3254         match nodes_2_event {
3255                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3256                         assert_eq!(channel_id, chan_2.2);
3257                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3258                 },
3259                 _ => panic!("Unexpected event"),
3260         }
3261
3262         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3263         match nodes_0_event {
3264                 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, .. } } => {
3265                         assert!(update_add_htlcs.is_empty());
3266                         assert_eq!(update_fail_htlcs.len(), 3);
3267                         assert!(update_fulfill_htlcs.is_empty());
3268                         assert!(update_fail_malformed_htlcs.is_empty());
3269                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3270
3271                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3272                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3273                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3274
3275                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3276
3277                         let events = nodes[0].node.get_and_clear_pending_events();
3278                         assert_eq!(events.len(), 6);
3279                         match events[0] {
3280                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3281                                         assert!(failed_htlcs.insert(payment_hash.0));
3282                                         // If we delivered B's RAA we got an unknown preimage error, not something
3283                                         // that we should update our routing table for.
3284                                         if !deliver_bs_raa {
3285                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3286                                         }
3287                                 },
3288                                 _ => panic!("Unexpected event"),
3289                         }
3290                         match events[1] {
3291                                 Event::PaymentFailed { ref payment_hash, .. } => {
3292                                         assert_eq!(*payment_hash, first_payment_hash);
3293                                 },
3294                                 _ => panic!("Unexpected event"),
3295                         }
3296                         match events[2] {
3297                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3298                                         assert!(failed_htlcs.insert(payment_hash.0));
3299                                 },
3300                                 _ => panic!("Unexpected event"),
3301                         }
3302                         match events[3] {
3303                                 Event::PaymentFailed { ref payment_hash, .. } => {
3304                                         assert_eq!(*payment_hash, second_payment_hash);
3305                                 },
3306                                 _ => panic!("Unexpected event"),
3307                         }
3308                         match events[4] {
3309                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3310                                         assert!(failed_htlcs.insert(payment_hash.0));
3311                                 },
3312                                 _ => panic!("Unexpected event"),
3313                         }
3314                         match events[5] {
3315                                 Event::PaymentFailed { ref payment_hash, .. } => {
3316                                         assert_eq!(*payment_hash, third_payment_hash);
3317                                 },
3318                                 _ => panic!("Unexpected event"),
3319                         }
3320                 },
3321                 _ => panic!("Unexpected event"),
3322         }
3323
3324         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3325         match events[0] {
3326                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3327                 _ => panic!("Unexpected event"),
3328         }
3329
3330         assert!(failed_htlcs.contains(&first_payment_hash.0));
3331         assert!(failed_htlcs.contains(&second_payment_hash.0));
3332         assert!(failed_htlcs.contains(&third_payment_hash.0));
3333 }
3334
3335 #[test]
3336 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3337         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3338         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3339         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3340         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3341 }
3342
3343 #[test]
3344 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3345         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3346         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3347         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3348         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3349 }
3350
3351 #[test]
3352 fn fail_backward_pending_htlc_upon_channel_failure() {
3353         let chanmon_cfgs = create_chanmon_cfgs(2);
3354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3356         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3357         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3358
3359         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3360         {
3361                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3362                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3363                         PaymentId(payment_hash.0)).unwrap();
3364                 check_added_monitors!(nodes[0], 1);
3365
3366                 let payment_event = {
3367                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3368                         assert_eq!(events.len(), 1);
3369                         SendEvent::from_event(events.remove(0))
3370                 };
3371                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3372                 assert_eq!(payment_event.msgs.len(), 1);
3373         }
3374
3375         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3376         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3377         {
3378                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3379                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3380                 check_added_monitors!(nodes[0], 0);
3381
3382                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3383         }
3384
3385         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3386         {
3387                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3388
3389                 let secp_ctx = Secp256k1::new();
3390                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3391                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3392                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3393                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3394                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3395                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3396
3397                 // Send a 0-msat update_add_htlc to fail the channel.
3398                 let update_add_htlc = msgs::UpdateAddHTLC {
3399                         channel_id: chan.2,
3400                         htlc_id: 0,
3401                         amount_msat: 0,
3402                         payment_hash,
3403                         cltv_expiry,
3404                         onion_routing_packet,
3405                 };
3406                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3407         }
3408         let events = nodes[0].node.get_and_clear_pending_events();
3409         assert_eq!(events.len(), 3);
3410         // Check that Alice fails backward the pending HTLC from the second payment.
3411         match events[0] {
3412                 Event::PaymentPathFailed { payment_hash, .. } => {
3413                         assert_eq!(payment_hash, failed_payment_hash);
3414                 },
3415                 _ => panic!("Unexpected event"),
3416         }
3417         match events[1] {
3418                 Event::PaymentFailed { payment_hash, .. } => {
3419                         assert_eq!(payment_hash, failed_payment_hash);
3420                 },
3421                 _ => panic!("Unexpected event"),
3422         }
3423         match events[2] {
3424                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3425                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3426                 },
3427                 _ => panic!("Unexpected event {:?}", events[1]),
3428         }
3429         check_closed_broadcast!(nodes[0], true);
3430         check_added_monitors!(nodes[0], 1);
3431 }
3432
3433 #[test]
3434 fn test_htlc_ignore_latest_remote_commitment() {
3435         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3436         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3437         let chanmon_cfgs = create_chanmon_cfgs(2);
3438         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3439         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3440         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3441         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3442                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3443                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3444                 // connect_style.
3445                 return;
3446         }
3447         create_announced_chan_between_nodes(&nodes, 0, 1);
3448
3449         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3450         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3451         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3452         check_closed_broadcast!(nodes[0], true);
3453         check_added_monitors!(nodes[0], 1);
3454         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3455
3456         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3457         assert_eq!(node_txn.len(), 3);
3458         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3459
3460         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3461         connect_block(&nodes[1], &block);
3462         check_closed_broadcast!(nodes[1], true);
3463         check_added_monitors!(nodes[1], 1);
3464         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3465
3466         // Duplicate the connect_block call since this may happen due to other listeners
3467         // registering new transactions
3468         connect_block(&nodes[1], &block);
3469 }
3470
3471 #[test]
3472 fn test_force_close_fail_back() {
3473         // Check which HTLCs are failed-backwards on channel force-closure
3474         let chanmon_cfgs = create_chanmon_cfgs(3);
3475         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3476         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3477         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3478         create_announced_chan_between_nodes(&nodes, 0, 1);
3479         create_announced_chan_between_nodes(&nodes, 1, 2);
3480
3481         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3482
3483         let mut payment_event = {
3484                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3485                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3486                 check_added_monitors!(nodes[0], 1);
3487
3488                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3489                 assert_eq!(events.len(), 1);
3490                 SendEvent::from_event(events.remove(0))
3491         };
3492
3493         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3494         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3495
3496         expect_pending_htlcs_forwardable!(nodes[1]);
3497
3498         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3499         assert_eq!(events_2.len(), 1);
3500         payment_event = SendEvent::from_event(events_2.remove(0));
3501         assert_eq!(payment_event.msgs.len(), 1);
3502
3503         check_added_monitors!(nodes[1], 1);
3504         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3505         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3506         check_added_monitors!(nodes[2], 1);
3507         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3508
3509         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3510         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3511         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3512
3513         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3514         check_closed_broadcast!(nodes[2], true);
3515         check_added_monitors!(nodes[2], 1);
3516         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3517         let tx = {
3518                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3519                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3520                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3521                 // back to nodes[1] upon timeout otherwise.
3522                 assert_eq!(node_txn.len(), 1);
3523                 node_txn.remove(0)
3524         };
3525
3526         mine_transaction(&nodes[1], &tx);
3527
3528         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3529         check_closed_broadcast!(nodes[1], true);
3530         check_added_monitors!(nodes[1], 1);
3531         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3532
3533         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3534         {
3535                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3536                         .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);
3537         }
3538         mine_transaction(&nodes[2], &tx);
3539         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3540         assert_eq!(node_txn.len(), 1);
3541         assert_eq!(node_txn[0].input.len(), 1);
3542         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3543         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3544         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3545
3546         check_spends!(node_txn[0], tx);
3547 }
3548
3549 #[test]
3550 fn test_dup_events_on_peer_disconnect() {
3551         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3552         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3553         // as we used to generate the event immediately upon receipt of the payment preimage in the
3554         // update_fulfill_htlc message.
3555
3556         let chanmon_cfgs = create_chanmon_cfgs(2);
3557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3559         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3560         create_announced_chan_between_nodes(&nodes, 0, 1);
3561
3562         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3563
3564         nodes[1].node.claim_funds(payment_preimage);
3565         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3566         check_added_monitors!(nodes[1], 1);
3567         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3568         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3569         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3570
3571         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3572         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3573
3574         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575         expect_payment_path_successful!(nodes[0]);
3576 }
3577
3578 #[test]
3579 fn test_peer_disconnected_before_funding_broadcasted() {
3580         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3581         // before the funding transaction has been broadcasted.
3582         let chanmon_cfgs = create_chanmon_cfgs(2);
3583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3585         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3586
3587         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3588         // broadcasted, even though it's created by `nodes[0]`.
3589         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();
3590         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3591         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3592         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3593         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3594
3595         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3596         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3597
3598         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3599
3600         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3601         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3602
3603         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3604         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3605         // broadcasted.
3606         {
3607                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3608         }
3609
3610         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3611         // disconnected before the funding transaction was broadcasted.
3612         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3613         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3614
3615         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3616         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3617 }
3618
3619 #[test]
3620 fn test_simple_peer_disconnect() {
3621         // Test that we can reconnect when there are no lost messages
3622         let chanmon_cfgs = create_chanmon_cfgs(3);
3623         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3624         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3625         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3626         create_announced_chan_between_nodes(&nodes, 0, 1);
3627         create_announced_chan_between_nodes(&nodes, 1, 2);
3628
3629         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3630         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3631         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3632
3633         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3634         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3635         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3636         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3637
3638         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3639         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3640         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3641
3642         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3643         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3644         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3645         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3646
3647         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3648         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3649
3650         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3651         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3652
3653         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3654         {
3655                 let events = nodes[0].node.get_and_clear_pending_events();
3656                 assert_eq!(events.len(), 4);
3657                 match events[0] {
3658                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3659                                 assert_eq!(payment_preimage, payment_preimage_3);
3660                                 assert_eq!(payment_hash, payment_hash_3);
3661                         },
3662                         _ => panic!("Unexpected event"),
3663                 }
3664                 match events[1] {
3665                         Event::PaymentPathSuccessful { .. } => {},
3666                         _ => panic!("Unexpected event"),
3667                 }
3668                 match events[2] {
3669                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3670                                 assert_eq!(payment_hash, payment_hash_5);
3671                                 assert!(payment_failed_permanently);
3672                         },
3673                         _ => panic!("Unexpected event"),
3674                 }
3675                 match events[3] {
3676                         Event::PaymentFailed { payment_hash, .. } => {
3677                                 assert_eq!(payment_hash, payment_hash_5);
3678                         },
3679                         _ => panic!("Unexpected event"),
3680                 }
3681         }
3682
3683         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3684         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3685 }
3686
3687 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3688         // Test that we can reconnect when in-flight HTLC updates get dropped
3689         let chanmon_cfgs = create_chanmon_cfgs(2);
3690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3692         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3693
3694         let mut as_channel_ready = None;
3695         let channel_id = if messages_delivered == 0 {
3696                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3697                 as_channel_ready = Some(channel_ready);
3698                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3699                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3700                 // it before the channel_reestablish message.
3701                 chan_id
3702         } else {
3703                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3704         };
3705
3706         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3707
3708         let payment_event = {
3709                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3710                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3711                 check_added_monitors!(nodes[0], 1);
3712
3713                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3714                 assert_eq!(events.len(), 1);
3715                 SendEvent::from_event(events.remove(0))
3716         };
3717         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3718
3719         if messages_delivered < 2 {
3720                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3721         } else {
3722                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3723                 if messages_delivered >= 3 {
3724                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3725                         check_added_monitors!(nodes[1], 1);
3726                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3727
3728                         if messages_delivered >= 4 {
3729                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3730                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3731                                 check_added_monitors!(nodes[0], 1);
3732
3733                                 if messages_delivered >= 5 {
3734                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3735                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3736                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3737                                         check_added_monitors!(nodes[0], 1);
3738
3739                                         if messages_delivered >= 6 {
3740                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3741                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3742                                                 check_added_monitors!(nodes[1], 1);
3743                                         }
3744                                 }
3745                         }
3746                 }
3747         }
3748
3749         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3750         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3751         if messages_delivered < 3 {
3752                 if simulate_broken_lnd {
3753                         // lnd has a long-standing bug where they send a channel_ready prior to a
3754                         // channel_reestablish if you reconnect prior to channel_ready time.
3755                         //
3756                         // Here we simulate that behavior, delivering a channel_ready immediately on
3757                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3758                         // in `reconnect_nodes` but we currently don't fail based on that.
3759                         //
3760                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3761                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3762                 }
3763                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3764                 // received on either side, both sides will need to resend them.
3765                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3766         } else if messages_delivered == 3 {
3767                 // nodes[0] still wants its RAA + commitment_signed
3768                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3769         } else if messages_delivered == 4 {
3770                 // nodes[0] still wants its commitment_signed
3771                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3772         } else if messages_delivered == 5 {
3773                 // nodes[1] still wants its final RAA
3774                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3775         } else if messages_delivered == 6 {
3776                 // Everything was delivered...
3777                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3778         }
3779
3780         let events_1 = nodes[1].node.get_and_clear_pending_events();
3781         if messages_delivered == 0 {
3782                 assert_eq!(events_1.len(), 2);
3783                 match events_1[0] {
3784                         Event::ChannelReady { .. } => { },
3785                         _ => panic!("Unexpected event"),
3786                 };
3787                 match events_1[1] {
3788                         Event::PendingHTLCsForwardable { .. } => { },
3789                         _ => panic!("Unexpected event"),
3790                 };
3791         } else {
3792                 assert_eq!(events_1.len(), 1);
3793                 match events_1[0] {
3794                         Event::PendingHTLCsForwardable { .. } => { },
3795                         _ => panic!("Unexpected event"),
3796                 };
3797         }
3798
3799         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3800         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3801         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3802
3803         nodes[1].node.process_pending_htlc_forwards();
3804
3805         let events_2 = nodes[1].node.get_and_clear_pending_events();
3806         assert_eq!(events_2.len(), 1);
3807         match events_2[0] {
3808                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3809                         assert_eq!(payment_hash_1, *payment_hash);
3810                         assert_eq!(amount_msat, 1_000_000);
3811                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3812                         assert_eq!(via_channel_id, Some(channel_id));
3813                         match &purpose {
3814                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3815                                         assert!(payment_preimage.is_none());
3816                                         assert_eq!(payment_secret_1, *payment_secret);
3817                                 },
3818                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3819                         }
3820                 },
3821                 _ => panic!("Unexpected event"),
3822         }
3823
3824         nodes[1].node.claim_funds(payment_preimage_1);
3825         check_added_monitors!(nodes[1], 1);
3826         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3827
3828         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3829         assert_eq!(events_3.len(), 1);
3830         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3831                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3832                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3833                         assert!(updates.update_add_htlcs.is_empty());
3834                         assert!(updates.update_fail_htlcs.is_empty());
3835                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3836                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3837                         assert!(updates.update_fee.is_none());
3838                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3839                 },
3840                 _ => panic!("Unexpected event"),
3841         };
3842
3843         if messages_delivered >= 1 {
3844                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3845
3846                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3847                 assert_eq!(events_4.len(), 1);
3848                 match events_4[0] {
3849                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3850                                 assert_eq!(payment_preimage_1, *payment_preimage);
3851                                 assert_eq!(payment_hash_1, *payment_hash);
3852                         },
3853                         _ => panic!("Unexpected event"),
3854                 }
3855
3856                 if messages_delivered >= 2 {
3857                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3858                         check_added_monitors!(nodes[0], 1);
3859                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3860
3861                         if messages_delivered >= 3 {
3862                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3863                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3864                                 check_added_monitors!(nodes[1], 1);
3865
3866                                 if messages_delivered >= 4 {
3867                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3868                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3869                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3870                                         check_added_monitors!(nodes[1], 1);
3871
3872                                         if messages_delivered >= 5 {
3873                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3874                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3875                                                 check_added_monitors!(nodes[0], 1);
3876                                         }
3877                                 }
3878                         }
3879                 }
3880         }
3881
3882         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3883         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3884         if messages_delivered < 2 {
3885                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3886                 if messages_delivered < 1 {
3887                         expect_payment_sent!(nodes[0], payment_preimage_1);
3888                 } else {
3889                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3890                 }
3891         } else if messages_delivered == 2 {
3892                 // nodes[0] still wants its RAA + commitment_signed
3893                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3894         } else if messages_delivered == 3 {
3895                 // nodes[0] still wants its commitment_signed
3896                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3897         } else if messages_delivered == 4 {
3898                 // nodes[1] still wants its final RAA
3899                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3900         } else if messages_delivered == 5 {
3901                 // Everything was delivered...
3902                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3903         }
3904
3905         if messages_delivered == 1 || messages_delivered == 2 {
3906                 expect_payment_path_successful!(nodes[0]);
3907         }
3908         if messages_delivered <= 5 {
3909                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3910                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3911         }
3912         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3913
3914         if messages_delivered > 2 {
3915                 expect_payment_path_successful!(nodes[0]);
3916         }
3917
3918         // Channel should still work fine...
3919         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3920         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3921         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3922 }
3923
3924 #[test]
3925 fn test_drop_messages_peer_disconnect_a() {
3926         do_test_drop_messages_peer_disconnect(0, true);
3927         do_test_drop_messages_peer_disconnect(0, false);
3928         do_test_drop_messages_peer_disconnect(1, false);
3929         do_test_drop_messages_peer_disconnect(2, false);
3930 }
3931
3932 #[test]
3933 fn test_drop_messages_peer_disconnect_b() {
3934         do_test_drop_messages_peer_disconnect(3, false);
3935         do_test_drop_messages_peer_disconnect(4, false);
3936         do_test_drop_messages_peer_disconnect(5, false);
3937         do_test_drop_messages_peer_disconnect(6, false);
3938 }
3939
3940 #[test]
3941 fn test_channel_ready_without_best_block_updated() {
3942         // Previously, if we were offline when a funding transaction was locked in, and then we came
3943         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3944         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3945         // channel_ready immediately instead.
3946         let chanmon_cfgs = create_chanmon_cfgs(2);
3947         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3948         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3949         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3950         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3951
3952         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3953
3954         let conf_height = nodes[0].best_block_info().1 + 1;
3955         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3956         let block_txn = [funding_tx];
3957         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3958         let conf_block_header = nodes[0].get_block_header(conf_height);
3959         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3960
3961         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3962         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3963         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3964 }
3965
3966 #[test]
3967 fn test_drop_messages_peer_disconnect_dual_htlc() {
3968         // Test that we can handle reconnecting when both sides of a channel have pending
3969         // commitment_updates when we disconnect.
3970         let chanmon_cfgs = create_chanmon_cfgs(2);
3971         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3972         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3973         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3974         create_announced_chan_between_nodes(&nodes, 0, 1);
3975
3976         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3977
3978         // Now try to send a second payment which will fail to send
3979         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3980         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3981                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3982         check_added_monitors!(nodes[0], 1);
3983
3984         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3985         assert_eq!(events_1.len(), 1);
3986         match events_1[0] {
3987                 MessageSendEvent::UpdateHTLCs { .. } => {},
3988                 _ => panic!("Unexpected event"),
3989         }
3990
3991         nodes[1].node.claim_funds(payment_preimage_1);
3992         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3993         check_added_monitors!(nodes[1], 1);
3994
3995         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3996         assert_eq!(events_2.len(), 1);
3997         match events_2[0] {
3998                 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 } } => {
3999                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4000                         assert!(update_add_htlcs.is_empty());
4001                         assert_eq!(update_fulfill_htlcs.len(), 1);
4002                         assert!(update_fail_htlcs.is_empty());
4003                         assert!(update_fail_malformed_htlcs.is_empty());
4004                         assert!(update_fee.is_none());
4005
4006                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4007                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4008                         assert_eq!(events_3.len(), 1);
4009                         match events_3[0] {
4010                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4011                                         assert_eq!(*payment_preimage, payment_preimage_1);
4012                                         assert_eq!(*payment_hash, payment_hash_1);
4013                                 },
4014                                 _ => panic!("Unexpected event"),
4015                         }
4016
4017                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4018                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4019                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4020                         check_added_monitors!(nodes[0], 1);
4021                 },
4022                 _ => panic!("Unexpected event"),
4023         }
4024
4025         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4026         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4027
4028         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();
4029         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4030         assert_eq!(reestablish_1.len(), 1);
4031         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();
4032         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4033         assert_eq!(reestablish_2.len(), 1);
4034
4035         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4036         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4037         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4038         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4039
4040         assert!(as_resp.0.is_none());
4041         assert!(bs_resp.0.is_none());
4042
4043         assert!(bs_resp.1.is_none());
4044         assert!(bs_resp.2.is_none());
4045
4046         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4047
4048         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4049         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4050         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4051         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4052         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4053         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4054         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4055         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4056         // No commitment_signed so get_event_msg's assert(len == 1) passes
4057         check_added_monitors!(nodes[1], 1);
4058
4059         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4060         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4061         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4062         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4063         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4064         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4065         assert!(bs_second_commitment_signed.update_fee.is_none());
4066         check_added_monitors!(nodes[1], 1);
4067
4068         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4069         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4070         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4071         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4072         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4073         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4074         assert!(as_commitment_signed.update_fee.is_none());
4075         check_added_monitors!(nodes[0], 1);
4076
4077         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4078         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4079         // No commitment_signed so get_event_msg's assert(len == 1) passes
4080         check_added_monitors!(nodes[0], 1);
4081
4082         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4083         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4084         // No commitment_signed so get_event_msg's assert(len == 1) passes
4085         check_added_monitors!(nodes[1], 1);
4086
4087         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4088         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4089         check_added_monitors!(nodes[1], 1);
4090
4091         expect_pending_htlcs_forwardable!(nodes[1]);
4092
4093         let events_5 = nodes[1].node.get_and_clear_pending_events();
4094         assert_eq!(events_5.len(), 1);
4095         match events_5[0] {
4096                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4097                         assert_eq!(payment_hash_2, *payment_hash);
4098                         match &purpose {
4099                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4100                                         assert!(payment_preimage.is_none());
4101                                         assert_eq!(payment_secret_2, *payment_secret);
4102                                 },
4103                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4104                         }
4105                 },
4106                 _ => panic!("Unexpected event"),
4107         }
4108
4109         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4110         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4111         check_added_monitors!(nodes[0], 1);
4112
4113         expect_payment_path_successful!(nodes[0]);
4114         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4115 }
4116
4117 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4118         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4119         // to avoid our counterparty failing the channel.
4120         let chanmon_cfgs = create_chanmon_cfgs(2);
4121         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4122         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4123         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4124
4125         create_announced_chan_between_nodes(&nodes, 0, 1);
4126
4127         let our_payment_hash = if send_partial_mpp {
4128                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4129                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4130                 // indicates there are more HTLCs coming.
4131                 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.
4132                 let payment_id = PaymentId([42; 32]);
4133                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4134                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4135                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4136                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4137                         &None, session_privs[0]).unwrap();
4138                 check_added_monitors!(nodes[0], 1);
4139                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4140                 assert_eq!(events.len(), 1);
4141                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4142                 // hop should *not* yet generate any PaymentClaimable event(s).
4143                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4144                 our_payment_hash
4145         } else {
4146                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4147         };
4148
4149         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4150         connect_block(&nodes[0], &block);
4151         connect_block(&nodes[1], &block);
4152         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4153         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4154                 block.header.prev_blockhash = block.block_hash();
4155                 connect_block(&nodes[0], &block);
4156                 connect_block(&nodes[1], &block);
4157         }
4158
4159         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4160
4161         check_added_monitors!(nodes[1], 1);
4162         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4163         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4164         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4165         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4166         assert!(htlc_timeout_updates.update_fee.is_none());
4167
4168         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4169         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4170         // 100_000 msat as u64, followed by the height at which we failed back above
4171         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4172         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4173         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4174 }
4175
4176 #[test]
4177 fn test_htlc_timeout() {
4178         do_test_htlc_timeout(true);
4179         do_test_htlc_timeout(false);
4180 }
4181
4182 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4183         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4184         let chanmon_cfgs = create_chanmon_cfgs(3);
4185         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4186         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4187         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4188         create_announced_chan_between_nodes(&nodes, 0, 1);
4189         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4190
4191         // Make sure all nodes are at the same starting height
4192         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4193         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4194         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4195
4196         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4197         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4198         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4199                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4200         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4201         check_added_monitors!(nodes[1], 1);
4202
4203         // Now attempt to route a second payment, which should be placed in the holding cell
4204         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4205         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4206         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4207                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4208         if forwarded_htlc {
4209                 check_added_monitors!(nodes[0], 1);
4210                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4211                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4212                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4213                 expect_pending_htlcs_forwardable!(nodes[1]);
4214         }
4215         check_added_monitors!(nodes[1], 0);
4216
4217         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4218         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4219         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4220         connect_blocks(&nodes[1], 1);
4221
4222         if forwarded_htlc {
4223                 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 }]);
4224                 check_added_monitors!(nodes[1], 1);
4225                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4226                 assert_eq!(fail_commit.len(), 1);
4227                 match fail_commit[0] {
4228                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4229                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4230                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4231                         },
4232                         _ => unreachable!(),
4233                 }
4234                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4235         } else {
4236                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4237         }
4238 }
4239
4240 #[test]
4241 fn test_holding_cell_htlc_add_timeouts() {
4242         do_test_holding_cell_htlc_add_timeouts(false);
4243         do_test_holding_cell_htlc_add_timeouts(true);
4244 }
4245
4246 macro_rules! check_spendable_outputs {
4247         ($node: expr, $keysinterface: expr) => {
4248                 {
4249                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4250                         let mut txn = Vec::new();
4251                         let mut all_outputs = Vec::new();
4252                         let secp_ctx = Secp256k1::new();
4253                         for event in events.drain(..) {
4254                                 match event {
4255                                         Event::SpendableOutputs { mut outputs } => {
4256                                                 for outp in outputs.drain(..) {
4257                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4258                                                         all_outputs.push(outp);
4259                                                 }
4260                                         },
4261                                         _ => panic!("Unexpected event"),
4262                                 };
4263                         }
4264                         if all_outputs.len() > 1 {
4265                                 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, None, &secp_ctx) {
4266                                         txn.push(tx);
4267                                 }
4268                         }
4269                         txn
4270                 }
4271         }
4272 }
4273
4274 #[test]
4275 fn test_claim_sizeable_push_msat() {
4276         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4277         let chanmon_cfgs = create_chanmon_cfgs(2);
4278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4280         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4281
4282         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4283         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4284         check_closed_broadcast!(nodes[1], true);
4285         check_added_monitors!(nodes[1], 1);
4286         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4287         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4288         assert_eq!(node_txn.len(), 1);
4289         check_spends!(node_txn[0], chan.3);
4290         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
4291
4292         mine_transaction(&nodes[1], &node_txn[0]);
4293         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4294
4295         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4296         assert_eq!(spend_txn.len(), 1);
4297         assert_eq!(spend_txn[0].input.len(), 1);
4298         check_spends!(spend_txn[0], node_txn[0]);
4299         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4300 }
4301
4302 #[test]
4303 fn test_claim_on_remote_sizeable_push_msat() {
4304         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4305         // to_remote output is encumbered by a P2WPKH
4306         let chanmon_cfgs = create_chanmon_cfgs(2);
4307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4309         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4310
4311         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4312         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4313         check_closed_broadcast!(nodes[0], true);
4314         check_added_monitors!(nodes[0], 1);
4315         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4316
4317         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4318         assert_eq!(node_txn.len(), 1);
4319         check_spends!(node_txn[0], chan.3);
4320         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
4321
4322         mine_transaction(&nodes[1], &node_txn[0]);
4323         check_closed_broadcast!(nodes[1], true);
4324         check_added_monitors!(nodes[1], 1);
4325         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4326         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4327
4328         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4329         assert_eq!(spend_txn.len(), 1);
4330         check_spends!(spend_txn[0], node_txn[0]);
4331 }
4332
4333 #[test]
4334 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4335         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4336         // to_remote output is encumbered by a P2WPKH
4337
4338         let chanmon_cfgs = create_chanmon_cfgs(2);
4339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4341         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4342
4343         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4344         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4345         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4346         assert_eq!(revoked_local_txn[0].input.len(), 1);
4347         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4348
4349         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4350         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4351         check_closed_broadcast!(nodes[1], true);
4352         check_added_monitors!(nodes[1], 1);
4353         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4354
4355         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4356         mine_transaction(&nodes[1], &node_txn[0]);
4357         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4358
4359         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4360         assert_eq!(spend_txn.len(), 3);
4361         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4362         check_spends!(spend_txn[1], node_txn[0]);
4363         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4364 }
4365
4366 #[test]
4367 fn test_static_spendable_outputs_preimage_tx() {
4368         let chanmon_cfgs = create_chanmon_cfgs(2);
4369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4371         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4372
4373         // Create some initial channels
4374         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4375
4376         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4377
4378         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4379         assert_eq!(commitment_tx[0].input.len(), 1);
4380         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4381
4382         // Settle A's commitment tx on B's chain
4383         nodes[1].node.claim_funds(payment_preimage);
4384         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4385         check_added_monitors!(nodes[1], 1);
4386         mine_transaction(&nodes[1], &commitment_tx[0]);
4387         check_added_monitors!(nodes[1], 1);
4388         let events = nodes[1].node.get_and_clear_pending_msg_events();
4389         match events[0] {
4390                 MessageSendEvent::UpdateHTLCs { .. } => {},
4391                 _ => panic!("Unexpected event"),
4392         }
4393         match events[1] {
4394                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4395                 _ => panic!("Unexepected event"),
4396         }
4397
4398         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4399         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4400         assert_eq!(node_txn.len(), 1);
4401         check_spends!(node_txn[0], commitment_tx[0]);
4402         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4403
4404         mine_transaction(&nodes[1], &node_txn[0]);
4405         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4406         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4407
4408         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4409         assert_eq!(spend_txn.len(), 1);
4410         check_spends!(spend_txn[0], node_txn[0]);
4411 }
4412
4413 #[test]
4414 fn test_static_spendable_outputs_timeout_tx() {
4415         let chanmon_cfgs = create_chanmon_cfgs(2);
4416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4419
4420         // Create some initial channels
4421         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4422
4423         // Rebalance the network a bit by relaying one payment through all the channels ...
4424         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4425
4426         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4427
4428         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4429         assert_eq!(commitment_tx[0].input.len(), 1);
4430         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4431
4432         // Settle A's commitment tx on B' chain
4433         mine_transaction(&nodes[1], &commitment_tx[0]);
4434         check_added_monitors!(nodes[1], 1);
4435         let events = nodes[1].node.get_and_clear_pending_msg_events();
4436         match events[0] {
4437                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4438                 _ => panic!("Unexpected event"),
4439         }
4440         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4441
4442         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4443         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4444         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4445         check_spends!(node_txn[0],  commitment_tx[0].clone());
4446         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4447
4448         mine_transaction(&nodes[1], &node_txn[0]);
4449         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4450         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4451         expect_payment_failed!(nodes[1], our_payment_hash, false);
4452
4453         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4454         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4455         check_spends!(spend_txn[0], commitment_tx[0]);
4456         check_spends!(spend_txn[1], node_txn[0]);
4457         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4458 }
4459
4460 #[test]
4461 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4462         let chanmon_cfgs = create_chanmon_cfgs(2);
4463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4466
4467         // Create some initial channels
4468         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4469
4470         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4471         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4472         assert_eq!(revoked_local_txn[0].input.len(), 1);
4473         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4474
4475         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4476
4477         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4478         check_closed_broadcast!(nodes[1], true);
4479         check_added_monitors!(nodes[1], 1);
4480         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4481
4482         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4483         assert_eq!(node_txn.len(), 1);
4484         assert_eq!(node_txn[0].input.len(), 2);
4485         check_spends!(node_txn[0], revoked_local_txn[0]);
4486
4487         mine_transaction(&nodes[1], &node_txn[0]);
4488         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4489
4490         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4491         assert_eq!(spend_txn.len(), 1);
4492         check_spends!(spend_txn[0], node_txn[0]);
4493 }
4494
4495 #[test]
4496 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4497         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4498         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4501         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4502
4503         // Create some initial channels
4504         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4505
4506         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4507         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4508         assert_eq!(revoked_local_txn[0].input.len(), 1);
4509         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4510
4511         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4512
4513         // A will generate HTLC-Timeout from revoked commitment tx
4514         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4515         check_closed_broadcast!(nodes[0], true);
4516         check_added_monitors!(nodes[0], 1);
4517         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4518         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4519
4520         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4521         assert_eq!(revoked_htlc_txn.len(), 1);
4522         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4523         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4524         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4525         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4526
4527         // B will generate justice tx from A's revoked commitment/HTLC tx
4528         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4529         check_closed_broadcast!(nodes[1], true);
4530         check_added_monitors!(nodes[1], 1);
4531         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4532
4533         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4534         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4535         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4536         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4537         // transactions next...
4538         assert_eq!(node_txn[0].input.len(), 3);
4539         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4540
4541         assert_eq!(node_txn[1].input.len(), 2);
4542         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4543         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4544                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4545         } else {
4546                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4547                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4548         }
4549
4550         mine_transaction(&nodes[1], &node_txn[1]);
4551         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4552
4553         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4554         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4555         assert_eq!(spend_txn.len(), 1);
4556         assert_eq!(spend_txn[0].input.len(), 1);
4557         check_spends!(spend_txn[0], node_txn[1]);
4558 }
4559
4560 #[test]
4561 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4562         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4563         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4567
4568         // Create some initial channels
4569         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4570
4571         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4572         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4573         assert_eq!(revoked_local_txn[0].input.len(), 1);
4574         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4575
4576         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4577         assert_eq!(revoked_local_txn[0].output.len(), 2);
4578
4579         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4580
4581         // B will generate HTLC-Success from revoked commitment tx
4582         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4583         check_closed_broadcast!(nodes[1], true);
4584         check_added_monitors!(nodes[1], 1);
4585         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4586         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4587
4588         assert_eq!(revoked_htlc_txn.len(), 1);
4589         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4590         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4591         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4592
4593         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4594         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4595         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4596
4597         // A will generate justice tx from B's revoked commitment/HTLC tx
4598         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4599         check_closed_broadcast!(nodes[0], true);
4600         check_added_monitors!(nodes[0], 1);
4601         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4602
4603         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4604         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4605
4606         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4607         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4608         // transactions next...
4609         assert_eq!(node_txn[0].input.len(), 2);
4610         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4611         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4612                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4613         } else {
4614                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4615                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4616         }
4617
4618         assert_eq!(node_txn[1].input.len(), 1);
4619         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4620
4621         mine_transaction(&nodes[0], &node_txn[1]);
4622         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4623
4624         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4625         // didn't try to generate any new transactions.
4626
4627         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4628         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4629         assert_eq!(spend_txn.len(), 3);
4630         assert_eq!(spend_txn[0].input.len(), 1);
4631         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4632         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4633         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4634         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4635 }
4636
4637 #[test]
4638 fn test_onchain_to_onchain_claim() {
4639         // Test that in case of channel closure, we detect the state of output and claim HTLC
4640         // on downstream peer's remote commitment tx.
4641         // First, have C claim an HTLC against its own latest commitment transaction.
4642         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4643         // channel.
4644         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4645         // gets broadcast.
4646
4647         let chanmon_cfgs = create_chanmon_cfgs(3);
4648         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4649         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4650         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4651
4652         // Create some initial channels
4653         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4654         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4655
4656         // Ensure all nodes are at the same height
4657         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4658         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4659         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4660         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4661
4662         // Rebalance the network a bit by relaying one payment through all the channels ...
4663         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4664         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4665
4666         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4667         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4668         check_spends!(commitment_tx[0], chan_2.3);
4669         nodes[2].node.claim_funds(payment_preimage);
4670         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4671         check_added_monitors!(nodes[2], 1);
4672         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4673         assert!(updates.update_add_htlcs.is_empty());
4674         assert!(updates.update_fail_htlcs.is_empty());
4675         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4676         assert!(updates.update_fail_malformed_htlcs.is_empty());
4677
4678         mine_transaction(&nodes[2], &commitment_tx[0]);
4679         check_closed_broadcast!(nodes[2], true);
4680         check_added_monitors!(nodes[2], 1);
4681         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4682
4683         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4684         assert_eq!(c_txn.len(), 1);
4685         check_spends!(c_txn[0], commitment_tx[0]);
4686         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4687         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4688         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4689
4690         // 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
4691         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4692         check_added_monitors!(nodes[1], 1);
4693         let events = nodes[1].node.get_and_clear_pending_events();
4694         assert_eq!(events.len(), 2);
4695         match events[0] {
4696                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4697                 _ => panic!("Unexpected event"),
4698         }
4699         match events[1] {
4700                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4701                         assert_eq!(fee_earned_msat, Some(1000));
4702                         assert_eq!(prev_channel_id, Some(chan_1.2));
4703                         assert_eq!(claim_from_onchain_tx, true);
4704                         assert_eq!(next_channel_id, Some(chan_2.2));
4705                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4706                 },
4707                 _ => panic!("Unexpected event"),
4708         }
4709         check_added_monitors!(nodes[1], 1);
4710         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4711         assert_eq!(msg_events.len(), 3);
4712         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4713         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4714
4715         match nodes_2_event {
4716                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4717                 _ => panic!("Unexpected event"),
4718         }
4719
4720         match nodes_0_event {
4721                 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, .. } } => {
4722                         assert!(update_add_htlcs.is_empty());
4723                         assert!(update_fail_htlcs.is_empty());
4724                         assert_eq!(update_fulfill_htlcs.len(), 1);
4725                         assert!(update_fail_malformed_htlcs.is_empty());
4726                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4727                 },
4728                 _ => panic!("Unexpected event"),
4729         };
4730
4731         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4732         match msg_events[0] {
4733                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4734                 _ => panic!("Unexpected event"),
4735         }
4736
4737         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4738         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4739         mine_transaction(&nodes[1], &commitment_tx[0]);
4740         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4741         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4742         // ChannelMonitor: HTLC-Success tx
4743         assert_eq!(b_txn.len(), 1);
4744         check_spends!(b_txn[0], commitment_tx[0]);
4745         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4746         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4747         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4748
4749         check_closed_broadcast!(nodes[1], true);
4750         check_added_monitors!(nodes[1], 1);
4751 }
4752
4753 #[test]
4754 fn test_duplicate_payment_hash_one_failure_one_success() {
4755         // Topology : A --> B --> C --> D
4756         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4757         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4758         // we forward one of the payments onwards to D.
4759         let chanmon_cfgs = create_chanmon_cfgs(4);
4760         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4761         // When this test was written, the default base fee floated based on the HTLC count.
4762         // It is now fixed, so we simply set the fee to the expected value here.
4763         let mut config = test_default_channel_config();
4764         config.channel_config.forwarding_fee_base_msat = 196;
4765         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4766                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4767         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4768
4769         create_announced_chan_between_nodes(&nodes, 0, 1);
4770         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4771         create_announced_chan_between_nodes(&nodes, 2, 3);
4772
4773         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4774         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4775         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4776         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4777         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4778
4779         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4780
4781         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4782         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4783         // script push size limit so that the below script length checks match
4784         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4785         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4786                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4787         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4788         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4789
4790         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4791         assert_eq!(commitment_txn[0].input.len(), 1);
4792         check_spends!(commitment_txn[0], chan_2.3);
4793
4794         mine_transaction(&nodes[1], &commitment_txn[0]);
4795         check_closed_broadcast!(nodes[1], true);
4796         check_added_monitors!(nodes[1], 1);
4797         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4798         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4799
4800         let htlc_timeout_tx;
4801         { // Extract one of the two HTLC-Timeout transaction
4802                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4803                 // ChannelMonitor: timeout tx * 2-or-3
4804                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4805
4806                 check_spends!(node_txn[0], commitment_txn[0]);
4807                 assert_eq!(node_txn[0].input.len(), 1);
4808                 assert_eq!(node_txn[0].output.len(), 1);
4809
4810                 if node_txn.len() > 2 {
4811                         check_spends!(node_txn[1], commitment_txn[0]);
4812                         assert_eq!(node_txn[1].input.len(), 1);
4813                         assert_eq!(node_txn[1].output.len(), 1);
4814                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4815
4816                         check_spends!(node_txn[2], commitment_txn[0]);
4817                         assert_eq!(node_txn[2].input.len(), 1);
4818                         assert_eq!(node_txn[2].output.len(), 1);
4819                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4820                 } else {
4821                         check_spends!(node_txn[1], commitment_txn[0]);
4822                         assert_eq!(node_txn[1].input.len(), 1);
4823                         assert_eq!(node_txn[1].output.len(), 1);
4824                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4825                 }
4826
4827                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4828                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4829                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4830                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4831                 if node_txn.len() > 2 {
4832                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4833                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4834                 } else {
4835                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4836                 }
4837         }
4838
4839         nodes[2].node.claim_funds(our_payment_preimage);
4840         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4841
4842         mine_transaction(&nodes[2], &commitment_txn[0]);
4843         check_added_monitors!(nodes[2], 2);
4844         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4845         let events = nodes[2].node.get_and_clear_pending_msg_events();
4846         match events[0] {
4847                 MessageSendEvent::UpdateHTLCs { .. } => {},
4848                 _ => panic!("Unexpected event"),
4849         }
4850         match events[1] {
4851                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4852                 _ => panic!("Unexepected event"),
4853         }
4854         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4855         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4856         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4857         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4858         assert_eq!(htlc_success_txn[0].input.len(), 1);
4859         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4860         assert_eq!(htlc_success_txn[1].input.len(), 1);
4861         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4862         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4863         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4864
4865         mine_transaction(&nodes[1], &htlc_timeout_tx);
4866         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4867         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 }]);
4868         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4869         assert!(htlc_updates.update_add_htlcs.is_empty());
4870         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4871         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4872         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4873         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4874         check_added_monitors!(nodes[1], 1);
4875
4876         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4877         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4878         {
4879                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4880         }
4881         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4882
4883         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4884         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4885         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4886         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4887         assert!(updates.update_add_htlcs.is_empty());
4888         assert!(updates.update_fail_htlcs.is_empty());
4889         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4890         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4891         assert!(updates.update_fail_malformed_htlcs.is_empty());
4892         check_added_monitors!(nodes[1], 1);
4893
4894         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4895         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4896         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4897 }
4898
4899 #[test]
4900 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4901         let chanmon_cfgs = create_chanmon_cfgs(2);
4902         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4903         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4904         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4905
4906         // Create some initial channels
4907         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4908
4909         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4910         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4911         assert_eq!(local_txn.len(), 1);
4912         assert_eq!(local_txn[0].input.len(), 1);
4913         check_spends!(local_txn[0], chan_1.3);
4914
4915         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4916         nodes[1].node.claim_funds(payment_preimage);
4917         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4918         check_added_monitors!(nodes[1], 1);
4919
4920         mine_transaction(&nodes[1], &local_txn[0]);
4921         check_added_monitors!(nodes[1], 1);
4922         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4923         let events = nodes[1].node.get_and_clear_pending_msg_events();
4924         match events[0] {
4925                 MessageSendEvent::UpdateHTLCs { .. } => {},
4926                 _ => panic!("Unexpected event"),
4927         }
4928         match events[1] {
4929                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4930                 _ => panic!("Unexepected event"),
4931         }
4932         let node_tx = {
4933                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4934                 assert_eq!(node_txn.len(), 1);
4935                 assert_eq!(node_txn[0].input.len(), 1);
4936                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4937                 check_spends!(node_txn[0], local_txn[0]);
4938                 node_txn[0].clone()
4939         };
4940
4941         mine_transaction(&nodes[1], &node_tx);
4942         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4943
4944         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4945         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4946         assert_eq!(spend_txn.len(), 1);
4947         assert_eq!(spend_txn[0].input.len(), 1);
4948         check_spends!(spend_txn[0], node_tx);
4949         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4950 }
4951
4952 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4953         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4954         // unrevoked commitment transaction.
4955         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4956         // a remote RAA before they could be failed backwards (and combinations thereof).
4957         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4958         // use the same payment hashes.
4959         // Thus, we use a six-node network:
4960         //
4961         // A \         / E
4962         //    - C - D -
4963         // B /         \ F
4964         // And test where C fails back to A/B when D announces its latest commitment transaction
4965         let chanmon_cfgs = create_chanmon_cfgs(6);
4966         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4967         // When this test was written, the default base fee floated based on the HTLC count.
4968         // It is now fixed, so we simply set the fee to the expected value here.
4969         let mut config = test_default_channel_config();
4970         config.channel_config.forwarding_fee_base_msat = 196;
4971         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4972                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4973         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4974
4975         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4976         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4977         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4978         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4979         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4980
4981         // Rebalance and check output sanity...
4982         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4983         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4984         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4985
4986         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4987                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4988         // 0th HTLC:
4989         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
4990         // 1st HTLC:
4991         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
4992         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4993         // 2nd HTLC:
4994         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
4995         // 3rd HTLC:
4996         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
4997         // 4th HTLC:
4998         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4999         // 5th HTLC:
5000         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5001         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5002         // 6th HTLC:
5003         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());
5004         // 7th HTLC:
5005         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());
5006
5007         // 8th HTLC:
5008         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5009         // 9th HTLC:
5010         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5011         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
5012
5013         // 10th HTLC:
5014         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
5015         // 11th HTLC:
5016         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5017         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());
5018
5019         // Double-check that six of the new HTLC were added
5020         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5021         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5022         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5023         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5024
5025         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5026         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5027         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5028         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5029         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5030         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5031         check_added_monitors!(nodes[4], 0);
5032
5033         let failed_destinations = vec![
5034                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5035                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5036                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5037                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5038         ];
5039         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5040         check_added_monitors!(nodes[4], 1);
5041
5042         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5043         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5044         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5045         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5046         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5047         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5048
5049         // Fail 3rd below-dust and 7th above-dust HTLCs
5050         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5051         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5052         check_added_monitors!(nodes[5], 0);
5053
5054         let failed_destinations_2 = vec![
5055                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5056                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5057         ];
5058         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5059         check_added_monitors!(nodes[5], 1);
5060
5061         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5062         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5063         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5064         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5065
5066         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5067
5068         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5069         let failed_destinations_3 = vec![
5070                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5071                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5072                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5073                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5074                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5075                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5076         ];
5077         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5078         check_added_monitors!(nodes[3], 1);
5079         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5080         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5081         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5082         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5083         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5084         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5085         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5086         if deliver_last_raa {
5087                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5088         } else {
5089                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5090         }
5091
5092         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5093         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5094         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5095         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5096         //
5097         // We now broadcast the latest commitment transaction, which *should* result in failures for
5098         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5099         // the non-broadcast above-dust HTLCs.
5100         //
5101         // Alternatively, we may broadcast the previous commitment transaction, which should only
5102         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5103         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5104
5105         if announce_latest {
5106                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5107         } else {
5108                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5109         }
5110         let events = nodes[2].node.get_and_clear_pending_events();
5111         let close_event = if deliver_last_raa {
5112                 assert_eq!(events.len(), 2 + 6);
5113                 events.last().clone().unwrap()
5114         } else {
5115                 assert_eq!(events.len(), 1);
5116                 events.last().clone().unwrap()
5117         };
5118         match close_event {
5119                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5120                 _ => panic!("Unexpected event"),
5121         }
5122
5123         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5124         check_closed_broadcast!(nodes[2], true);
5125         if deliver_last_raa {
5126                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5127
5128                 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();
5129                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5130         } else {
5131                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5132                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5133                 } else {
5134                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5135                 };
5136
5137                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5138         }
5139         check_added_monitors!(nodes[2], 3);
5140
5141         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5142         assert_eq!(cs_msgs.len(), 2);
5143         let mut a_done = false;
5144         for msg in cs_msgs {
5145                 match msg {
5146                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5147                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5148                                 // should be failed-backwards here.
5149                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5150                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5151                                         for htlc in &updates.update_fail_htlcs {
5152                                                 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 });
5153                                         }
5154                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5155                                         assert!(!a_done);
5156                                         a_done = true;
5157                                         &nodes[0]
5158                                 } else {
5159                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5160                                         for htlc in &updates.update_fail_htlcs {
5161                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5162                                         }
5163                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5164                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5165                                         &nodes[1]
5166                                 };
5167                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5168                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5169                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5170                                 if announce_latest {
5171                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5172                                         if *node_id == nodes[0].node.get_our_node_id() {
5173                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5174                                         }
5175                                 }
5176                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5177                         },
5178                         _ => panic!("Unexpected event"),
5179                 }
5180         }
5181
5182         let as_events = nodes[0].node.get_and_clear_pending_events();
5183         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5184         let mut as_failds = HashSet::new();
5185         let mut as_updates = 0;
5186         for event in as_events.iter() {
5187                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5188                         assert!(as_failds.insert(*payment_hash));
5189                         if *payment_hash != payment_hash_2 {
5190                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5191                         } else {
5192                                 assert!(!payment_failed_permanently);
5193                         }
5194                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5195                                 as_updates += 1;
5196                         }
5197                 } else if let &Event::PaymentFailed { .. } = event {
5198                 } else { panic!("Unexpected event"); }
5199         }
5200         assert!(as_failds.contains(&payment_hash_1));
5201         assert!(as_failds.contains(&payment_hash_2));
5202         if announce_latest {
5203                 assert!(as_failds.contains(&payment_hash_3));
5204                 assert!(as_failds.contains(&payment_hash_5));
5205         }
5206         assert!(as_failds.contains(&payment_hash_6));
5207
5208         let bs_events = nodes[1].node.get_and_clear_pending_events();
5209         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5210         let mut bs_failds = HashSet::new();
5211         let mut bs_updates = 0;
5212         for event in bs_events.iter() {
5213                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5214                         assert!(bs_failds.insert(*payment_hash));
5215                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5216                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5217                         } else {
5218                                 assert!(!payment_failed_permanently);
5219                         }
5220                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5221                                 bs_updates += 1;
5222                         }
5223                 } else if let &Event::PaymentFailed { .. } = event {
5224                 } else { panic!("Unexpected event"); }
5225         }
5226         assert!(bs_failds.contains(&payment_hash_1));
5227         assert!(bs_failds.contains(&payment_hash_2));
5228         if announce_latest {
5229                 assert!(bs_failds.contains(&payment_hash_4));
5230         }
5231         assert!(bs_failds.contains(&payment_hash_5));
5232
5233         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5234         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5235         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5236         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5237         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5238         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5239 }
5240
5241 #[test]
5242 fn test_fail_backwards_latest_remote_announce_a() {
5243         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5244 }
5245
5246 #[test]
5247 fn test_fail_backwards_latest_remote_announce_b() {
5248         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5249 }
5250
5251 #[test]
5252 fn test_fail_backwards_previous_remote_announce() {
5253         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5254         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5255         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5256 }
5257
5258 #[test]
5259 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5260         let chanmon_cfgs = create_chanmon_cfgs(2);
5261         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5262         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5263         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5264
5265         // Create some initial channels
5266         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5267
5268         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5269         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5270         assert_eq!(local_txn[0].input.len(), 1);
5271         check_spends!(local_txn[0], chan_1.3);
5272
5273         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5274         mine_transaction(&nodes[0], &local_txn[0]);
5275         check_closed_broadcast!(nodes[0], true);
5276         check_added_monitors!(nodes[0], 1);
5277         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5278         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5279
5280         let htlc_timeout = {
5281                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5282                 assert_eq!(node_txn.len(), 1);
5283                 assert_eq!(node_txn[0].input.len(), 1);
5284                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5285                 check_spends!(node_txn[0], local_txn[0]);
5286                 node_txn[0].clone()
5287         };
5288
5289         mine_transaction(&nodes[0], &htlc_timeout);
5290         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5291         expect_payment_failed!(nodes[0], our_payment_hash, false);
5292
5293         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5294         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5295         assert_eq!(spend_txn.len(), 3);
5296         check_spends!(spend_txn[0], local_txn[0]);
5297         assert_eq!(spend_txn[1].input.len(), 1);
5298         check_spends!(spend_txn[1], htlc_timeout);
5299         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5300         assert_eq!(spend_txn[2].input.len(), 2);
5301         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5302         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5303                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5304 }
5305
5306 #[test]
5307 fn test_key_derivation_params() {
5308         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5309         // manager rotation to test that `channel_keys_id` returned in
5310         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5311         // then derive a `delayed_payment_key`.
5312
5313         let chanmon_cfgs = create_chanmon_cfgs(3);
5314
5315         // We manually create the node configuration to backup the seed.
5316         let seed = [42; 32];
5317         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5318         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);
5319         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5320         let scorer = Mutex::new(test_utils::TestScorer::new());
5321         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5322         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)) };
5323         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5324         node_cfgs.remove(0);
5325         node_cfgs.insert(0, node);
5326
5327         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5328         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5329
5330         // Create some initial channels
5331         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5332         // for node 0
5333         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5334         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5335         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5336
5337         // Ensure all nodes are at the same height
5338         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5339         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5340         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5341         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5342
5343         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5344         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5345         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5346         assert_eq!(local_txn_1[0].input.len(), 1);
5347         check_spends!(local_txn_1[0], chan_1.3);
5348
5349         // We check funding pubkey are unique
5350         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]));
5351         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]));
5352         if from_0_funding_key_0 == from_1_funding_key_0
5353             || from_0_funding_key_0 == from_1_funding_key_1
5354             || from_0_funding_key_1 == from_1_funding_key_0
5355             || from_0_funding_key_1 == from_1_funding_key_1 {
5356                 panic!("Funding pubkeys aren't unique");
5357         }
5358
5359         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5360         mine_transaction(&nodes[0], &local_txn_1[0]);
5361         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5362         check_closed_broadcast!(nodes[0], true);
5363         check_added_monitors!(nodes[0], 1);
5364         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5365
5366         let htlc_timeout = {
5367                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5368                 assert_eq!(node_txn.len(), 1);
5369                 assert_eq!(node_txn[0].input.len(), 1);
5370                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5371                 check_spends!(node_txn[0], local_txn_1[0]);
5372                 node_txn[0].clone()
5373         };
5374
5375         mine_transaction(&nodes[0], &htlc_timeout);
5376         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5377         expect_payment_failed!(nodes[0], our_payment_hash, false);
5378
5379         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5380         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5381         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5382         assert_eq!(spend_txn.len(), 3);
5383         check_spends!(spend_txn[0], local_txn_1[0]);
5384         assert_eq!(spend_txn[1].input.len(), 1);
5385         check_spends!(spend_txn[1], htlc_timeout);
5386         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5387         assert_eq!(spend_txn[2].input.len(), 2);
5388         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5389         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5390                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5391 }
5392
5393 #[test]
5394 fn test_static_output_closing_tx() {
5395         let chanmon_cfgs = create_chanmon_cfgs(2);
5396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5398         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5399
5400         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5401
5402         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5403         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5404
5405         mine_transaction(&nodes[0], &closing_tx);
5406         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5407         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5408
5409         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5410         assert_eq!(spend_txn.len(), 1);
5411         check_spends!(spend_txn[0], closing_tx);
5412
5413         mine_transaction(&nodes[1], &closing_tx);
5414         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5415         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5416
5417         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5418         assert_eq!(spend_txn.len(), 1);
5419         check_spends!(spend_txn[0], closing_tx);
5420 }
5421
5422 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5423         let chanmon_cfgs = create_chanmon_cfgs(2);
5424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5426         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5427         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5428
5429         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5430
5431         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5432         // present in B's local commitment transaction, but none of A's commitment transactions.
5433         nodes[1].node.claim_funds(payment_preimage);
5434         check_added_monitors!(nodes[1], 1);
5435         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5436
5437         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5438         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5439         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5440
5441         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5442         check_added_monitors!(nodes[0], 1);
5443         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5444         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5445         check_added_monitors!(nodes[1], 1);
5446
5447         let starting_block = nodes[1].best_block_info();
5448         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5449         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5450                 connect_block(&nodes[1], &block);
5451                 block.header.prev_blockhash = block.block_hash();
5452         }
5453         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5454         check_closed_broadcast!(nodes[1], true);
5455         check_added_monitors!(nodes[1], 1);
5456         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5457 }
5458
5459 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5460         let chanmon_cfgs = create_chanmon_cfgs(2);
5461         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5462         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5463         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5464         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5465
5466         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5467         nodes[0].node.send_payment_with_route(&route, payment_hash,
5468                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5469         check_added_monitors!(nodes[0], 1);
5470
5471         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5472
5473         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5474         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5475         // to "time out" the HTLC.
5476
5477         let starting_block = nodes[1].best_block_info();
5478         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5479
5480         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5481                 connect_block(&nodes[0], &block);
5482                 block.header.prev_blockhash = block.block_hash();
5483         }
5484         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5485         check_closed_broadcast!(nodes[0], true);
5486         check_added_monitors!(nodes[0], 1);
5487         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5488 }
5489
5490 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5491         let chanmon_cfgs = create_chanmon_cfgs(3);
5492         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5493         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5494         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5495         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5496
5497         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5498         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5499         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5500         // actually revoked.
5501         let htlc_value = if use_dust { 50000 } else { 3000000 };
5502         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5503         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5504         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5505         check_added_monitors!(nodes[1], 1);
5506
5507         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5508         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5509         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5510         check_added_monitors!(nodes[0], 1);
5511         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5512         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5513         check_added_monitors!(nodes[1], 1);
5514         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5515         check_added_monitors!(nodes[1], 1);
5516         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5517
5518         if check_revoke_no_close {
5519                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5520                 check_added_monitors!(nodes[0], 1);
5521         }
5522
5523         let starting_block = nodes[1].best_block_info();
5524         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5525         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5526                 connect_block(&nodes[0], &block);
5527                 block.header.prev_blockhash = block.block_hash();
5528         }
5529         if !check_revoke_no_close {
5530                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5531                 check_closed_broadcast!(nodes[0], true);
5532                 check_added_monitors!(nodes[0], 1);
5533                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5534         } else {
5535                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5536         }
5537 }
5538
5539 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5540 // There are only a few cases to test here:
5541 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5542 //    broadcastable commitment transactions result in channel closure,
5543 //  * its included in an unrevoked-but-previous remote commitment transaction,
5544 //  * its included in the latest remote or local commitment transactions.
5545 // We test each of the three possible commitment transactions individually and use both dust and
5546 // non-dust HTLCs.
5547 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5548 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5549 // tested for at least one of the cases in other tests.
5550 #[test]
5551 fn htlc_claim_single_commitment_only_a() {
5552         do_htlc_claim_local_commitment_only(true);
5553         do_htlc_claim_local_commitment_only(false);
5554
5555         do_htlc_claim_current_remote_commitment_only(true);
5556         do_htlc_claim_current_remote_commitment_only(false);
5557 }
5558
5559 #[test]
5560 fn htlc_claim_single_commitment_only_b() {
5561         do_htlc_claim_previous_remote_commitment_only(true, false);
5562         do_htlc_claim_previous_remote_commitment_only(false, false);
5563         do_htlc_claim_previous_remote_commitment_only(true, true);
5564         do_htlc_claim_previous_remote_commitment_only(false, true);
5565 }
5566
5567 #[test]
5568 #[should_panic]
5569 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5570         let chanmon_cfgs = create_chanmon_cfgs(2);
5571         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5572         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5573         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5574         // Force duplicate randomness for every get-random call
5575         for node in nodes.iter() {
5576                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5577         }
5578
5579         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5580         let channel_value_satoshis=10000;
5581         let push_msat=10001;
5582         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5583         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5584         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5585         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5586
5587         // Create a second channel with the same random values. This used to panic due to a colliding
5588         // channel_id, but now panics due to a colliding outbound SCID alias.
5589         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5590 }
5591
5592 #[test]
5593 fn bolt2_open_channel_sending_node_checks_part2() {
5594         let chanmon_cfgs = create_chanmon_cfgs(2);
5595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5597         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5598
5599         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5600         let channel_value_satoshis=2^24;
5601         let push_msat=10001;
5602         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5603
5604         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5605         let channel_value_satoshis=10000;
5606         // Test when push_msat is equal to 1000 * funding_satoshis.
5607         let push_msat=1000*channel_value_satoshis+1;
5608         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5609
5610         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5611         let channel_value_satoshis=10000;
5612         let push_msat=10001;
5613         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
5614         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5615         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5616
5617         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5618         // 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
5619         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5620
5621         // 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.
5622         assert!(BREAKDOWN_TIMEOUT>0);
5623         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5624
5625         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5626         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5627         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5628
5629         // 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.
5630         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5631         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5632         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5633         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5634         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5635 }
5636
5637 #[test]
5638 fn bolt2_open_channel_sane_dust_limit() {
5639         let chanmon_cfgs = create_chanmon_cfgs(2);
5640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5642         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5643
5644         let channel_value_satoshis=1000000;
5645         let push_msat=10001;
5646         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5647         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5648         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5649         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5650
5651         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5652         let events = nodes[1].node.get_and_clear_pending_msg_events();
5653         let err_msg = match events[0] {
5654                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5655                         msg.clone()
5656                 },
5657                 _ => panic!("Unexpected event"),
5658         };
5659         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5660 }
5661
5662 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5663 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5664 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5665 // is no longer affordable once it's freed.
5666 #[test]
5667 fn test_fail_holding_cell_htlc_upon_free() {
5668         let chanmon_cfgs = create_chanmon_cfgs(2);
5669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5671         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5672         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5673
5674         // First nodes[0] generates an update_fee, setting the channel's
5675         // pending_update_fee.
5676         {
5677                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5678                 *feerate_lock += 20;
5679         }
5680         nodes[0].node.timer_tick_occurred();
5681         check_added_monitors!(nodes[0], 1);
5682
5683         let events = nodes[0].node.get_and_clear_pending_msg_events();
5684         assert_eq!(events.len(), 1);
5685         let (update_msg, commitment_signed) = match events[0] {
5686                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5687                         (update_fee.as_ref(), commitment_signed)
5688                 },
5689                 _ => panic!("Unexpected event"),
5690         };
5691
5692         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5693
5694         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5695         let channel_reserve = chan_stat.channel_reserve_msat;
5696         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5697         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5698
5699         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5700         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5701         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5702
5703         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5704         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5705                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5706         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5707         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5708
5709         // Flush the pending fee update.
5710         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5711         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5712         check_added_monitors!(nodes[1], 1);
5713         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5714         check_added_monitors!(nodes[0], 1);
5715
5716         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5717         // HTLC, but now that the fee has been raised the payment will now fail, causing
5718         // us to surface its failure to the user.
5719         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5720         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5721         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);
5722         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 {}",
5723                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5724         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5725
5726         // Check that the payment failed to be sent out.
5727         let events = nodes[0].node.get_and_clear_pending_events();
5728         assert_eq!(events.len(), 2);
5729         match &events[0] {
5730                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5731                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5732                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5733                         assert_eq!(*payment_failed_permanently, false);
5734                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5735                 },
5736                 _ => panic!("Unexpected event"),
5737         }
5738         match &events[1] {
5739                 &Event::PaymentFailed { ref payment_hash, .. } => {
5740                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5741                 },
5742                 _ => panic!("Unexpected event"),
5743         }
5744 }
5745
5746 // Test that if multiple HTLCs are released from the holding cell and one is
5747 // valid but the other is no longer valid upon release, the valid HTLC can be
5748 // successfully completed while the other one fails as expected.
5749 #[test]
5750 fn test_free_and_fail_holding_cell_htlcs() {
5751         let chanmon_cfgs = create_chanmon_cfgs(2);
5752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5754         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5755         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5756
5757         // First nodes[0] generates an update_fee, setting the channel's
5758         // pending_update_fee.
5759         {
5760                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5761                 *feerate_lock += 200;
5762         }
5763         nodes[0].node.timer_tick_occurred();
5764         check_added_monitors!(nodes[0], 1);
5765
5766         let events = nodes[0].node.get_and_clear_pending_msg_events();
5767         assert_eq!(events.len(), 1);
5768         let (update_msg, commitment_signed) = match events[0] {
5769                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5770                         (update_fee.as_ref(), commitment_signed)
5771                 },
5772                 _ => panic!("Unexpected event"),
5773         };
5774
5775         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5776
5777         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5778         let channel_reserve = chan_stat.channel_reserve_msat;
5779         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5780         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5781
5782         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5783         let amt_1 = 20000;
5784         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5785         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5786         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5787
5788         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5789         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5790                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5791         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5792         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5793         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5794         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5795                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5796         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5797         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5798
5799         // Flush the pending fee update.
5800         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5801         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5802         check_added_monitors!(nodes[1], 1);
5803         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5804         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5805         check_added_monitors!(nodes[0], 2);
5806
5807         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5808         // but now that the fee has been raised the second payment will now fail, causing us
5809         // to surface its failure to the user. The first payment should succeed.
5810         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5811         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5812         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);
5813         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 {}",
5814                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5815         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5816
5817         // Check that the second payment failed to be sent out.
5818         let events = nodes[0].node.get_and_clear_pending_events();
5819         assert_eq!(events.len(), 2);
5820         match &events[0] {
5821                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5822                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5823                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5824                         assert_eq!(*payment_failed_permanently, false);
5825                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5826                 },
5827                 _ => panic!("Unexpected event"),
5828         }
5829         match &events[1] {
5830                 &Event::PaymentFailed { ref payment_hash, .. } => {
5831                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5832                 },
5833                 _ => panic!("Unexpected event"),
5834         }
5835
5836         // Complete the first payment and the RAA from the fee update.
5837         let (payment_event, send_raa_event) = {
5838                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5839                 assert_eq!(msgs.len(), 2);
5840                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5841         };
5842         let raa = match send_raa_event {
5843                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5844                 _ => panic!("Unexpected event"),
5845         };
5846         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5847         check_added_monitors!(nodes[1], 1);
5848         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5849         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5850         let events = nodes[1].node.get_and_clear_pending_events();
5851         assert_eq!(events.len(), 1);
5852         match events[0] {
5853                 Event::PendingHTLCsForwardable { .. } => {},
5854                 _ => panic!("Unexpected event"),
5855         }
5856         nodes[1].node.process_pending_htlc_forwards();
5857         let events = nodes[1].node.get_and_clear_pending_events();
5858         assert_eq!(events.len(), 1);
5859         match events[0] {
5860                 Event::PaymentClaimable { .. } => {},
5861                 _ => panic!("Unexpected event"),
5862         }
5863         nodes[1].node.claim_funds(payment_preimage_1);
5864         check_added_monitors!(nodes[1], 1);
5865         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5866
5867         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5868         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5869         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5870         expect_payment_sent!(nodes[0], payment_preimage_1);
5871 }
5872
5873 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5874 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5875 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5876 // once it's freed.
5877 #[test]
5878 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5879         let chanmon_cfgs = create_chanmon_cfgs(3);
5880         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5881         // When this test was written, the default base fee floated based on the HTLC count.
5882         // It is now fixed, so we simply set the fee to the expected value here.
5883         let mut config = test_default_channel_config();
5884         config.channel_config.forwarding_fee_base_msat = 196;
5885         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5886         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5887         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5888         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5889
5890         // First nodes[1] generates an update_fee, setting the channel's
5891         // pending_update_fee.
5892         {
5893                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5894                 *feerate_lock += 20;
5895         }
5896         nodes[1].node.timer_tick_occurred();
5897         check_added_monitors!(nodes[1], 1);
5898
5899         let events = nodes[1].node.get_and_clear_pending_msg_events();
5900         assert_eq!(events.len(), 1);
5901         let (update_msg, commitment_signed) = match events[0] {
5902                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5903                         (update_fee.as_ref(), commitment_signed)
5904                 },
5905                 _ => panic!("Unexpected event"),
5906         };
5907
5908         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5909
5910         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5911         let channel_reserve = chan_stat.channel_reserve_msat;
5912         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5913         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5914
5915         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5916         let feemsat = 239;
5917         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5918         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5919         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5920         let payment_event = {
5921                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5922                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5923                 check_added_monitors!(nodes[0], 1);
5924
5925                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5926                 assert_eq!(events.len(), 1);
5927
5928                 SendEvent::from_event(events.remove(0))
5929         };
5930         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5931         check_added_monitors!(nodes[1], 0);
5932         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5933         expect_pending_htlcs_forwardable!(nodes[1]);
5934
5935         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5936         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5937
5938         // Flush the pending fee update.
5939         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5940         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5941         check_added_monitors!(nodes[2], 1);
5942         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5943         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5944         check_added_monitors!(nodes[1], 2);
5945
5946         // A final RAA message is generated to finalize the fee update.
5947         let events = nodes[1].node.get_and_clear_pending_msg_events();
5948         assert_eq!(events.len(), 1);
5949
5950         let raa_msg = match &events[0] {
5951                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5952                         msg.clone()
5953                 },
5954                 _ => panic!("Unexpected event"),
5955         };
5956
5957         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5958         check_added_monitors!(nodes[2], 1);
5959         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5960
5961         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5962         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5963         assert_eq!(process_htlc_forwards_event.len(), 2);
5964         match &process_htlc_forwards_event[0] {
5965                 &Event::PendingHTLCsForwardable { .. } => {},
5966                 _ => panic!("Unexpected event"),
5967         }
5968
5969         // In response, we call ChannelManager's process_pending_htlc_forwards
5970         nodes[1].node.process_pending_htlc_forwards();
5971         check_added_monitors!(nodes[1], 1);
5972
5973         // This causes the HTLC to be failed backwards.
5974         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5975         assert_eq!(fail_event.len(), 1);
5976         let (fail_msg, commitment_signed) = match &fail_event[0] {
5977                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5978                         assert_eq!(updates.update_add_htlcs.len(), 0);
5979                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5980                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5981                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5982                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5983                 },
5984                 _ => panic!("Unexpected event"),
5985         };
5986
5987         // Pass the failure messages back to nodes[0].
5988         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5989         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5990
5991         // Complete the HTLC failure+removal process.
5992         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5993         check_added_monitors!(nodes[0], 1);
5994         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5995         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5996         check_added_monitors!(nodes[1], 2);
5997         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5998         assert_eq!(final_raa_event.len(), 1);
5999         let raa = match &final_raa_event[0] {
6000                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6001                 _ => panic!("Unexpected event"),
6002         };
6003         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6004         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6005         check_added_monitors!(nodes[0], 1);
6006 }
6007
6008 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6009 // 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.
6010 //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.
6011
6012 #[test]
6013 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6014         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6015         let chanmon_cfgs = create_chanmon_cfgs(2);
6016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6018         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6019         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6020
6021         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6022         route.paths[0].hops[0].fee_msat = 100;
6023
6024         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6025                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6026                 ), true, APIError::ChannelUnavailable { ref err },
6027                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6028         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6029         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6030 }
6031
6032 #[test]
6033 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6034         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6035         let chanmon_cfgs = create_chanmon_cfgs(2);
6036         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6037         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6038         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6039         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6040
6041         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6042         route.paths[0].hops[0].fee_msat = 0;
6043         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6044                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6045                 true, APIError::ChannelUnavailable { ref err },
6046                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6047
6048         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6049         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6050 }
6051
6052 #[test]
6053 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6054         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6055         let chanmon_cfgs = create_chanmon_cfgs(2);
6056         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6057         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6058         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6059         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6060
6061         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6062         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6063                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6064         check_added_monitors!(nodes[0], 1);
6065         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6066         updates.update_add_htlcs[0].amount_msat = 0;
6067
6068         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6069         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6070         check_closed_broadcast!(nodes[1], true).unwrap();
6071         check_added_monitors!(nodes[1], 1);
6072         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6073 }
6074
6075 #[test]
6076 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6077         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6078         //It is enforced when constructing a route.
6079         let chanmon_cfgs = create_chanmon_cfgs(2);
6080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6082         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6083         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6084
6085         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6086                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6087         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6088         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6089         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6090                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6091                 ), true, APIError::InvalidRoute { ref err },
6092                 assert_eq!(err, &"Channel CLTV overflowed?"));
6093 }
6094
6095 #[test]
6096 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6097         //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.
6098         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6099         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6100         let chanmon_cfgs = create_chanmon_cfgs(2);
6101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6103         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6104         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6105         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6106                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6107
6108         for i in 0..max_accepted_htlcs {
6109                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6110                 let payment_event = {
6111                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6112                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6113                         check_added_monitors!(nodes[0], 1);
6114
6115                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6116                         assert_eq!(events.len(), 1);
6117                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6118                                 assert_eq!(htlcs[0].htlc_id, i);
6119                         } else {
6120                                 assert!(false);
6121                         }
6122                         SendEvent::from_event(events.remove(0))
6123                 };
6124                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6125                 check_added_monitors!(nodes[1], 0);
6126                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6127
6128                 expect_pending_htlcs_forwardable!(nodes[1]);
6129                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6130         }
6131         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6132         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6133                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6134                 ), true, APIError::ChannelUnavailable { ref err },
6135                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6136
6137         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6138         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6139 }
6140
6141 #[test]
6142 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6143         //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.
6144         let chanmon_cfgs = create_chanmon_cfgs(2);
6145         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6146         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6147         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6148         let channel_value = 100000;
6149         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6150         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6151
6152         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6153
6154         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6155         // Manually create a route over our max in flight (which our router normally automatically
6156         // limits us to.
6157         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6158         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6159                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6160                 ), true, APIError::ChannelUnavailable { ref err },
6161                 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)));
6162
6163         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6164         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);
6165
6166         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6167 }
6168
6169 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6170 #[test]
6171 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6172         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6173         let chanmon_cfgs = create_chanmon_cfgs(2);
6174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6176         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6177         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6178         let htlc_minimum_msat: u64;
6179         {
6180                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6181                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6182                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6183                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6184         }
6185
6186         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6187         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6188                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6189         check_added_monitors!(nodes[0], 1);
6190         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6191         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6192         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6193         assert!(nodes[1].node.list_channels().is_empty());
6194         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6195         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()));
6196         check_added_monitors!(nodes[1], 1);
6197         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6198 }
6199
6200 #[test]
6201 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6202         //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
6203         let chanmon_cfgs = create_chanmon_cfgs(2);
6204         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6205         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6206         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6207         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6208
6209         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6210         let channel_reserve = chan_stat.channel_reserve_msat;
6211         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6212         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6213         // The 2* and +1 are for the fee spike reserve.
6214         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6215
6216         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6217         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6218         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6219                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6220         check_added_monitors!(nodes[0], 1);
6221         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6222
6223         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6224         // at this time channel-initiatee receivers are not required to enforce that senders
6225         // respect the fee_spike_reserve.
6226         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6227         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6228
6229         assert!(nodes[1].node.list_channels().is_empty());
6230         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6231         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6232         check_added_monitors!(nodes[1], 1);
6233         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6234 }
6235
6236 #[test]
6237 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6238         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6239         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6240         let chanmon_cfgs = create_chanmon_cfgs(2);
6241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6243         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6244         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6245
6246         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6247         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6248         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6249         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6250         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6251                 &route.paths[0], 3999999, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6252         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6253
6254         let mut msg = msgs::UpdateAddHTLC {
6255                 channel_id: chan.2,
6256                 htlc_id: 0,
6257                 amount_msat: 1000,
6258                 payment_hash: our_payment_hash,
6259                 cltv_expiry: htlc_cltv,
6260                 onion_routing_packet: onion_packet.clone(),
6261         };
6262
6263         for i in 0..50 {
6264                 msg.htlc_id = i as u64;
6265                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6266         }
6267         msg.htlc_id = (50) as u64;
6268         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6269
6270         assert!(nodes[1].node.list_channels().is_empty());
6271         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6272         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6273         check_added_monitors!(nodes[1], 1);
6274         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6275 }
6276
6277 #[test]
6278 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6279         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6280         let chanmon_cfgs = create_chanmon_cfgs(2);
6281         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6282         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6283         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6284         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6285
6286         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6287         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6288                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6289         check_added_monitors!(nodes[0], 1);
6290         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6291         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;
6292         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6293
6294         assert!(nodes[1].node.list_channels().is_empty());
6295         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6296         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6297         check_added_monitors!(nodes[1], 1);
6298         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6299 }
6300
6301 #[test]
6302 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6303         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6304         let chanmon_cfgs = create_chanmon_cfgs(2);
6305         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6306         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6307         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6308
6309         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6310         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6311         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6312                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6313         check_added_monitors!(nodes[0], 1);
6314         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6315         updates.update_add_htlcs[0].cltv_expiry = 500000000;
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_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
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_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6327         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6328         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6329         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6330         let chanmon_cfgs = create_chanmon_cfgs(2);
6331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6333         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6334
6335         create_announced_chan_between_nodes(&nodes, 0, 1);
6336         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6337         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6338                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6339         check_added_monitors!(nodes[0], 1);
6340         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6341         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6342
6343         //Disconnect and Reconnect
6344         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6345         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6346         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();
6347         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6348         assert_eq!(reestablish_1.len(), 1);
6349         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();
6350         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6351         assert_eq!(reestablish_2.len(), 1);
6352         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6353         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6354         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6355         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6356
6357         //Resend HTLC
6358         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6359         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6360         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6361         check_added_monitors!(nodes[1], 1);
6362         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6363
6364         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6365
6366         assert!(nodes[1].node.list_channels().is_empty());
6367         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6368         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6369         check_added_monitors!(nodes[1], 1);
6370         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6371 }
6372
6373 #[test]
6374 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6375         //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.
6376
6377         let chanmon_cfgs = create_chanmon_cfgs(2);
6378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6380         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6381         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6382         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6383         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6384                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6385
6386         check_added_monitors!(nodes[0], 1);
6387         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6388         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6389
6390         let update_msg = msgs::UpdateFulfillHTLC{
6391                 channel_id: chan.2,
6392                 htlc_id: 0,
6393                 payment_preimage: our_payment_preimage,
6394         };
6395
6396         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6397
6398         assert!(nodes[0].node.list_channels().is_empty());
6399         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6400         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()));
6401         check_added_monitors!(nodes[0], 1);
6402         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6403 }
6404
6405 #[test]
6406 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6407         //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.
6408
6409         let chanmon_cfgs = create_chanmon_cfgs(2);
6410         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6411         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6412         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6413         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6414
6415         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6416         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6417                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6418         check_added_monitors!(nodes[0], 1);
6419         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6420         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6421
6422         let update_msg = msgs::UpdateFailHTLC{
6423                 channel_id: chan.2,
6424                 htlc_id: 0,
6425                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6426         };
6427
6428         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6429
6430         assert!(nodes[0].node.list_channels().is_empty());
6431         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6432         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()));
6433         check_added_monitors!(nodes[0], 1);
6434         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6435 }
6436
6437 #[test]
6438 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6439         //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.
6440
6441         let chanmon_cfgs = create_chanmon_cfgs(2);
6442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6444         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6445         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6446
6447         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6448         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6449                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6450         check_added_monitors!(nodes[0], 1);
6451         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6452         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6453         let update_msg = msgs::UpdateFailMalformedHTLC{
6454                 channel_id: chan.2,
6455                 htlc_id: 0,
6456                 sha256_of_onion: [1; 32],
6457                 failure_code: 0x8000,
6458         };
6459
6460         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6461
6462         assert!(nodes[0].node.list_channels().is_empty());
6463         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6464         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()));
6465         check_added_monitors!(nodes[0], 1);
6466         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6467 }
6468
6469 #[test]
6470 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6471         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6472
6473         let chanmon_cfgs = create_chanmon_cfgs(2);
6474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6476         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6477         create_announced_chan_between_nodes(&nodes, 0, 1);
6478
6479         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6480
6481         nodes[1].node.claim_funds(our_payment_preimage);
6482         check_added_monitors!(nodes[1], 1);
6483         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6484
6485         let events = nodes[1].node.get_and_clear_pending_msg_events();
6486         assert_eq!(events.len(), 1);
6487         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6488                 match events[0] {
6489                         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, .. } } => {
6490                                 assert!(update_add_htlcs.is_empty());
6491                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6492                                 assert!(update_fail_htlcs.is_empty());
6493                                 assert!(update_fail_malformed_htlcs.is_empty());
6494                                 assert!(update_fee.is_none());
6495                                 update_fulfill_htlcs[0].clone()
6496                         },
6497                         _ => panic!("Unexpected event"),
6498                 }
6499         };
6500
6501         update_fulfill_msg.htlc_id = 1;
6502
6503         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6504
6505         assert!(nodes[0].node.list_channels().is_empty());
6506         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6507         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6508         check_added_monitors!(nodes[0], 1);
6509         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6510 }
6511
6512 #[test]
6513 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6514         //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.
6515
6516         let chanmon_cfgs = create_chanmon_cfgs(2);
6517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6520         create_announced_chan_between_nodes(&nodes, 0, 1);
6521
6522         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6523
6524         nodes[1].node.claim_funds(our_payment_preimage);
6525         check_added_monitors!(nodes[1], 1);
6526         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6527
6528         let events = nodes[1].node.get_and_clear_pending_msg_events();
6529         assert_eq!(events.len(), 1);
6530         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6531                 match events[0] {
6532                         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, .. } } => {
6533                                 assert!(update_add_htlcs.is_empty());
6534                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6535                                 assert!(update_fail_htlcs.is_empty());
6536                                 assert!(update_fail_malformed_htlcs.is_empty());
6537                                 assert!(update_fee.is_none());
6538                                 update_fulfill_htlcs[0].clone()
6539                         },
6540                         _ => panic!("Unexpected event"),
6541                 }
6542         };
6543
6544         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6545
6546         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6547
6548         assert!(nodes[0].node.list_channels().is_empty());
6549         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6550         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6551         check_added_monitors!(nodes[0], 1);
6552         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6553 }
6554
6555 #[test]
6556 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6557         //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.
6558
6559         let chanmon_cfgs = create_chanmon_cfgs(2);
6560         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6561         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6562         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6564
6565         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6566         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6567                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6568         check_added_monitors!(nodes[0], 1);
6569
6570         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6571         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6572
6573         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6574         check_added_monitors!(nodes[1], 0);
6575         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6576
6577         let events = nodes[1].node.get_and_clear_pending_msg_events();
6578
6579         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6580                 match events[0] {
6581                         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, .. } } => {
6582                                 assert!(update_add_htlcs.is_empty());
6583                                 assert!(update_fulfill_htlcs.is_empty());
6584                                 assert!(update_fail_htlcs.is_empty());
6585                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6586                                 assert!(update_fee.is_none());
6587                                 update_fail_malformed_htlcs[0].clone()
6588                         },
6589                         _ => panic!("Unexpected event"),
6590                 }
6591         };
6592         update_msg.failure_code &= !0x8000;
6593         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6594
6595         assert!(nodes[0].node.list_channels().is_empty());
6596         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6597         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6598         check_added_monitors!(nodes[0], 1);
6599         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6600 }
6601
6602 #[test]
6603 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6604         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6605         //    * 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.
6606
6607         let chanmon_cfgs = create_chanmon_cfgs(3);
6608         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6609         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6610         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6611         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6612         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6613
6614         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6615
6616         //First hop
6617         let mut payment_event = {
6618                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6619                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6620                 check_added_monitors!(nodes[0], 1);
6621                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6622                 assert_eq!(events.len(), 1);
6623                 SendEvent::from_event(events.remove(0))
6624         };
6625         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6626         check_added_monitors!(nodes[1], 0);
6627         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6628         expect_pending_htlcs_forwardable!(nodes[1]);
6629         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6630         assert_eq!(events_2.len(), 1);
6631         check_added_monitors!(nodes[1], 1);
6632         payment_event = SendEvent::from_event(events_2.remove(0));
6633         assert_eq!(payment_event.msgs.len(), 1);
6634
6635         //Second Hop
6636         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6637         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6638         check_added_monitors!(nodes[2], 0);
6639         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6640
6641         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6642         assert_eq!(events_3.len(), 1);
6643         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6644                 match events_3[0] {
6645                         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 } } => {
6646                                 assert!(update_add_htlcs.is_empty());
6647                                 assert!(update_fulfill_htlcs.is_empty());
6648                                 assert!(update_fail_htlcs.is_empty());
6649                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6650                                 assert!(update_fee.is_none());
6651                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6652                         },
6653                         _ => panic!("Unexpected event"),
6654                 }
6655         };
6656
6657         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6658
6659         check_added_monitors!(nodes[1], 0);
6660         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6661         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 }]);
6662         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6663         assert_eq!(events_4.len(), 1);
6664
6665         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6666         match events_4[0] {
6667                 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, .. } } => {
6668                         assert!(update_add_htlcs.is_empty());
6669                         assert!(update_fulfill_htlcs.is_empty());
6670                         assert_eq!(update_fail_htlcs.len(), 1);
6671                         assert!(update_fail_malformed_htlcs.is_empty());
6672                         assert!(update_fee.is_none());
6673                 },
6674                 _ => panic!("Unexpected event"),
6675         };
6676
6677         check_added_monitors!(nodes[1], 1);
6678 }
6679
6680 #[test]
6681 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6682         let chanmon_cfgs = create_chanmon_cfgs(3);
6683         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6684         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6685         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6686         create_announced_chan_between_nodes(&nodes, 0, 1);
6687         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6688
6689         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6690
6691         // First hop
6692         let mut payment_event = {
6693                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6694                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6695                 check_added_monitors!(nodes[0], 1);
6696                 SendEvent::from_node(&nodes[0])
6697         };
6698
6699         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6700         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6701         expect_pending_htlcs_forwardable!(nodes[1]);
6702         check_added_monitors!(nodes[1], 1);
6703         payment_event = SendEvent::from_node(&nodes[1]);
6704         assert_eq!(payment_event.msgs.len(), 1);
6705
6706         // Second Hop
6707         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6708         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6709         check_added_monitors!(nodes[2], 0);
6710         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6711
6712         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6713         assert_eq!(events_3.len(), 1);
6714         match events_3[0] {
6715                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6716                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6717                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6718                         update_msg.failure_code |= 0x2000;
6719
6720                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6721                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6722                 },
6723                 _ => panic!("Unexpected event"),
6724         }
6725
6726         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6727                 vec![HTLCDestination::NextHopChannel {
6728                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6729         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6730         assert_eq!(events_4.len(), 1);
6731         check_added_monitors!(nodes[1], 1);
6732
6733         match events_4[0] {
6734                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6735                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6736                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6737                 },
6738                 _ => panic!("Unexpected event"),
6739         }
6740
6741         let events_5 = nodes[0].node.get_and_clear_pending_events();
6742         assert_eq!(events_5.len(), 2);
6743
6744         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6745         // the node originating the error to its next hop.
6746         match events_5[0] {
6747                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6748                 } => {
6749                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6750                         assert!(is_permanent);
6751                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6752                 },
6753                 _ => panic!("Unexpected event"),
6754         }
6755         match events_5[1] {
6756                 Event::PaymentFailed { payment_hash, .. } => {
6757                         assert_eq!(payment_hash, our_payment_hash);
6758                 },
6759                 _ => panic!("Unexpected event"),
6760         }
6761
6762         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6763 }
6764
6765 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6766         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6767         // 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
6768         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6769
6770         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6771         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6776
6777         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6778                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6779
6780         // We route 2 dust-HTLCs between A and B
6781         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6782         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6783         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6784
6785         // Cache one local commitment tx as previous
6786         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6787
6788         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6789         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6790         check_added_monitors!(nodes[1], 0);
6791         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6792         check_added_monitors!(nodes[1], 1);
6793
6794         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6795         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6796         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6797         check_added_monitors!(nodes[0], 1);
6798
6799         // Cache one local commitment tx as lastest
6800         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6801
6802         let events = nodes[0].node.get_and_clear_pending_msg_events();
6803         match events[0] {
6804                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6805                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6806                 },
6807                 _ => panic!("Unexpected event"),
6808         }
6809         match events[1] {
6810                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6811                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6812                 },
6813                 _ => panic!("Unexpected event"),
6814         }
6815
6816         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6817         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6818         if announce_latest {
6819                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6820         } else {
6821                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6822         }
6823
6824         check_closed_broadcast!(nodes[0], true);
6825         check_added_monitors!(nodes[0], 1);
6826         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6827
6828         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6829         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6830         let events = nodes[0].node.get_and_clear_pending_events();
6831         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6832         assert_eq!(events.len(), 4);
6833         let mut first_failed = false;
6834         for event in events {
6835                 match event {
6836                         Event::PaymentPathFailed { payment_hash, .. } => {
6837                                 if payment_hash == payment_hash_1 {
6838                                         assert!(!first_failed);
6839                                         first_failed = true;
6840                                 } else {
6841                                         assert_eq!(payment_hash, payment_hash_2);
6842                                 }
6843                         },
6844                         Event::PaymentFailed { .. } => {}
6845                         _ => panic!("Unexpected event"),
6846                 }
6847         }
6848 }
6849
6850 #[test]
6851 fn test_failure_delay_dust_htlc_local_commitment() {
6852         do_test_failure_delay_dust_htlc_local_commitment(true);
6853         do_test_failure_delay_dust_htlc_local_commitment(false);
6854 }
6855
6856 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6857         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6858         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6859         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6860         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6861         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6862         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6863
6864         let chanmon_cfgs = create_chanmon_cfgs(3);
6865         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6866         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6867         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6868         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6869
6870         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6871                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6872
6873         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6874         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6875
6876         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6877         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6878
6879         // We revoked bs_commitment_tx
6880         if revoked {
6881                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6882                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6883         }
6884
6885         let mut timeout_tx = Vec::new();
6886         if local {
6887                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6888                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6889                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6890                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6891                 expect_payment_failed!(nodes[0], dust_hash, false);
6892
6893                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6894                 check_closed_broadcast!(nodes[0], true);
6895                 check_added_monitors!(nodes[0], 1);
6896                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6897                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6898                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6899                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6900                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6901                 mine_transaction(&nodes[0], &timeout_tx[0]);
6902                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6903                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6904         } else {
6905                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6906                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6907                 check_closed_broadcast!(nodes[0], true);
6908                 check_added_monitors!(nodes[0], 1);
6909                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6910                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6911
6912                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6913                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6914                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6915                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6916                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6917                 // dust HTLC should have been failed.
6918                 expect_payment_failed!(nodes[0], dust_hash, false);
6919
6920                 if !revoked {
6921                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6922                 } else {
6923                         assert_eq!(timeout_tx[0].lock_time.0, 11);
6924                 }
6925                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6926                 mine_transaction(&nodes[0], &timeout_tx[0]);
6927                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6928                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6929                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6930         }
6931 }
6932
6933 #[test]
6934 fn test_sweep_outbound_htlc_failure_update() {
6935         do_test_sweep_outbound_htlc_failure_update(false, true);
6936         do_test_sweep_outbound_htlc_failure_update(false, false);
6937         do_test_sweep_outbound_htlc_failure_update(true, false);
6938 }
6939
6940 #[test]
6941 fn test_user_configurable_csv_delay() {
6942         // We test our channel constructors yield errors when we pass them absurd csv delay
6943
6944         let mut low_our_to_self_config = UserConfig::default();
6945         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6946         let mut high_their_to_self_config = UserConfig::default();
6947         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6948         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6949         let chanmon_cfgs = create_chanmon_cfgs(2);
6950         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6951         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6952         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6953
6954         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6955         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6956                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6957                 &low_our_to_self_config, 0, 42)
6958         {
6959                 match error {
6960                         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())); },
6961                         _ => panic!("Unexpected event"),
6962                 }
6963         } else { assert!(false) }
6964
6965         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6966         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6967         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6968         open_channel.to_self_delay = 200;
6969         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6970                 &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,
6971                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6972         {
6973                 match error {
6974                         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()));  },
6975                         _ => panic!("Unexpected event"),
6976                 }
6977         } else { assert!(false); }
6978
6979         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6980         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6981         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()));
6982         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6983         accept_channel.to_self_delay = 200;
6984         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6985         let reason_msg;
6986         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6987                 match action {
6988                         &ErrorAction::SendErrorMessage { ref msg } => {
6989                                 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()));
6990                                 reason_msg = msg.data.clone();
6991                         },
6992                         _ => { panic!(); }
6993                 }
6994         } else { panic!(); }
6995         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6996
6997         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6998         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6999         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7000         open_channel.to_self_delay = 200;
7001         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7002                 &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,
7003                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7004         {
7005                 match error {
7006                         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())); },
7007                         _ => panic!("Unexpected event"),
7008                 }
7009         } else { assert!(false); }
7010 }
7011
7012 #[test]
7013 fn test_check_htlc_underpaying() {
7014         // Send payment through A -> B but A is maliciously
7015         // sending a probe payment (i.e less than expected value0
7016         // to B, B should refuse payment.
7017
7018         let chanmon_cfgs = create_chanmon_cfgs(2);
7019         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7020         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7021         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7022
7023         // Create some initial channels
7024         create_announced_chan_between_nodes(&nodes, 0, 1);
7025
7026         let scorer = test_utils::TestScorer::new();
7027         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7028         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7029         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7030         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7031         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7032         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7033                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7034         check_added_monitors!(nodes[0], 1);
7035
7036         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7037         assert_eq!(events.len(), 1);
7038         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7039         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7040         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7041
7042         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7043         // and then will wait a second random delay before failing the HTLC back:
7044         expect_pending_htlcs_forwardable!(nodes[1]);
7045         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7046
7047         // Node 3 is expecting payment of 100_000 but received 10_000,
7048         // it should fail htlc like we didn't know the preimage.
7049         nodes[1].node.process_pending_htlc_forwards();
7050
7051         let events = nodes[1].node.get_and_clear_pending_msg_events();
7052         assert_eq!(events.len(), 1);
7053         let (update_fail_htlc, commitment_signed) = match events[0] {
7054                 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 } } => {
7055                         assert!(update_add_htlcs.is_empty());
7056                         assert!(update_fulfill_htlcs.is_empty());
7057                         assert_eq!(update_fail_htlcs.len(), 1);
7058                         assert!(update_fail_malformed_htlcs.is_empty());
7059                         assert!(update_fee.is_none());
7060                         (update_fail_htlcs[0].clone(), commitment_signed)
7061                 },
7062                 _ => panic!("Unexpected event"),
7063         };
7064         check_added_monitors!(nodes[1], 1);
7065
7066         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7067         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7068
7069         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7070         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7071         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7072         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7073 }
7074
7075 #[test]
7076 fn test_announce_disable_channels() {
7077         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7078         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7079
7080         let chanmon_cfgs = create_chanmon_cfgs(2);
7081         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7082         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7083         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7084
7085         create_announced_chan_between_nodes(&nodes, 0, 1);
7086         create_announced_chan_between_nodes(&nodes, 1, 0);
7087         create_announced_chan_between_nodes(&nodes, 0, 1);
7088
7089         // Disconnect peers
7090         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7091         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7092
7093         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7094                 nodes[0].node.timer_tick_occurred();
7095         }
7096         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7097         assert_eq!(msg_events.len(), 3);
7098         let mut chans_disabled = HashMap::new();
7099         for e in msg_events {
7100                 match e {
7101                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7102                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7103                                 // Check that each channel gets updated exactly once
7104                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7105                                         panic!("Generated ChannelUpdate for wrong chan!");
7106                                 }
7107                         },
7108                         _ => panic!("Unexpected event"),
7109                 }
7110         }
7111         // Reconnect peers
7112         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();
7113         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7114         assert_eq!(reestablish_1.len(), 3);
7115         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();
7116         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7117         assert_eq!(reestablish_2.len(), 3);
7118
7119         // Reestablish chan_1
7120         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7121         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7122         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7123         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7124         // Reestablish chan_2
7125         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7126         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7127         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7128         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7129         // Reestablish chan_3
7130         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7131         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7132         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7133         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7134
7135         for _ in 0..ENABLE_GOSSIP_TICKS {
7136                 nodes[0].node.timer_tick_occurred();
7137         }
7138         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7139         nodes[0].node.timer_tick_occurred();
7140         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7141         assert_eq!(msg_events.len(), 3);
7142         for e in msg_events {
7143                 match e {
7144                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7145                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7146                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7147                                         // Each update should have a higher timestamp than the previous one, replacing
7148                                         // the old one.
7149                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7150                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7151                                 }
7152                         },
7153                         _ => panic!("Unexpected event"),
7154                 }
7155         }
7156         // Check that each channel gets updated exactly once
7157         assert!(chans_disabled.is_empty());
7158 }
7159
7160 #[test]
7161 fn test_bump_penalty_txn_on_revoked_commitment() {
7162         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7163         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7164
7165         let chanmon_cfgs = create_chanmon_cfgs(2);
7166         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7167         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7168         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7169
7170         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7171
7172         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7173         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7174                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7175         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7176         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7177
7178         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7179         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7180         assert_eq!(revoked_txn[0].output.len(), 4);
7181         assert_eq!(revoked_txn[0].input.len(), 1);
7182         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7183         let revoked_txid = revoked_txn[0].txid();
7184
7185         let mut penalty_sum = 0;
7186         for outp in revoked_txn[0].output.iter() {
7187                 if outp.script_pubkey.is_v0_p2wsh() {
7188                         penalty_sum += outp.value;
7189                 }
7190         }
7191
7192         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7193         let header_114 = connect_blocks(&nodes[1], 14);
7194
7195         // Actually revoke tx by claiming a HTLC
7196         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7197         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7198         check_added_monitors!(nodes[1], 1);
7199
7200         // One or more justice tx should have been broadcast, check it
7201         let penalty_1;
7202         let feerate_1;
7203         {
7204                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7205                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7206                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7207                 assert_eq!(node_txn[0].output.len(), 1);
7208                 check_spends!(node_txn[0], revoked_txn[0]);
7209                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7210                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7211                 penalty_1 = node_txn[0].txid();
7212                 node_txn.clear();
7213         };
7214
7215         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7216         connect_blocks(&nodes[1], 15);
7217         let mut penalty_2 = penalty_1;
7218         let mut feerate_2 = 0;
7219         {
7220                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7221                 assert_eq!(node_txn.len(), 1);
7222                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7223                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7224                         assert_eq!(node_txn[0].output.len(), 1);
7225                         check_spends!(node_txn[0], revoked_txn[0]);
7226                         penalty_2 = node_txn[0].txid();
7227                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7228                         assert_ne!(penalty_2, penalty_1);
7229                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7230                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7231                         // Verify 25% bump heuristic
7232                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7233                         node_txn.clear();
7234                 }
7235         }
7236         assert_ne!(feerate_2, 0);
7237
7238         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7239         connect_blocks(&nodes[1], 1);
7240         let penalty_3;
7241         let mut feerate_3 = 0;
7242         {
7243                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7244                 assert_eq!(node_txn.len(), 1);
7245                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7246                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7247                         assert_eq!(node_txn[0].output.len(), 1);
7248                         check_spends!(node_txn[0], revoked_txn[0]);
7249                         penalty_3 = node_txn[0].txid();
7250                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7251                         assert_ne!(penalty_3, penalty_2);
7252                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7253                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7254                         // Verify 25% bump heuristic
7255                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7256                         node_txn.clear();
7257                 }
7258         }
7259         assert_ne!(feerate_3, 0);
7260
7261         nodes[1].node.get_and_clear_pending_events();
7262         nodes[1].node.get_and_clear_pending_msg_events();
7263 }
7264
7265 #[test]
7266 fn test_bump_penalty_txn_on_revoked_htlcs() {
7267         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7268         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7269
7270         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7271         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7272         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7273         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7274         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7275
7276         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7277         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7278         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7279         let scorer = test_utils::TestScorer::new();
7280         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7281         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7282                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7283         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7284         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7285         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7286                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7287         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7288
7289         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7290         assert_eq!(revoked_local_txn[0].input.len(), 1);
7291         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7292
7293         // Revoke local commitment tx
7294         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7295
7296         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7297         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7298         check_closed_broadcast!(nodes[1], true);
7299         check_added_monitors!(nodes[1], 1);
7300         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7301         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7302
7303         let revoked_htlc_txn = {
7304                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7305                 assert_eq!(txn.len(), 2);
7306
7307                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7308                 assert_eq!(txn[0].input.len(), 1);
7309                 check_spends!(txn[0], revoked_local_txn[0]);
7310
7311                 assert_eq!(txn[1].input.len(), 1);
7312                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7313                 assert_eq!(txn[1].output.len(), 1);
7314                 check_spends!(txn[1], revoked_local_txn[0]);
7315
7316                 txn
7317         };
7318
7319         // Broadcast set of revoked txn on A
7320         let hash_128 = connect_blocks(&nodes[0], 40);
7321         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7322         connect_block(&nodes[0], &block_11);
7323         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7324         connect_block(&nodes[0], &block_129);
7325         let events = nodes[0].node.get_and_clear_pending_events();
7326         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7327         match events.last().unwrap() {
7328                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7329                 _ => panic!("Unexpected event"),
7330         }
7331         let first;
7332         let feerate_1;
7333         let penalty_txn;
7334         {
7335                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7336                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7337                 // Verify claim tx are spending revoked HTLC txn
7338
7339                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7340                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7341                 // which are included in the same block (they are broadcasted because we scan the
7342                 // transactions linearly and generate claims as we go, they likely should be removed in the
7343                 // future).
7344                 assert_eq!(node_txn[0].input.len(), 1);
7345                 check_spends!(node_txn[0], revoked_local_txn[0]);
7346                 assert_eq!(node_txn[1].input.len(), 1);
7347                 check_spends!(node_txn[1], revoked_local_txn[0]);
7348                 assert_eq!(node_txn[2].input.len(), 1);
7349                 check_spends!(node_txn[2], revoked_local_txn[0]);
7350
7351                 // Each of the three justice transactions claim a separate (single) output of the three
7352                 // available, which we check here:
7353                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7354                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7355                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7356
7357                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7358                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7359
7360                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7361                 // output, checked above).
7362                 assert_eq!(node_txn[3].input.len(), 2);
7363                 assert_eq!(node_txn[3].output.len(), 1);
7364                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7365
7366                 first = node_txn[3].txid();
7367                 // Store both feerates for later comparison
7368                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7369                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7370                 penalty_txn = vec![node_txn[2].clone()];
7371                 node_txn.clear();
7372         }
7373
7374         // Connect one more block to see if bumped penalty are issued for HTLC txn
7375         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7376         connect_block(&nodes[0], &block_130);
7377         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7378         connect_block(&nodes[0], &block_131);
7379
7380         // Few more blocks to confirm penalty txn
7381         connect_blocks(&nodes[0], 4);
7382         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7383         let header_144 = connect_blocks(&nodes[0], 9);
7384         let node_txn = {
7385                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7386                 assert_eq!(node_txn.len(), 1);
7387
7388                 assert_eq!(node_txn[0].input.len(), 2);
7389                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7390                 // Verify bumped tx is different and 25% bump heuristic
7391                 assert_ne!(first, node_txn[0].txid());
7392                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7393                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7394                 assert!(feerate_2 * 100 > feerate_1 * 125);
7395                 let txn = vec![node_txn[0].clone()];
7396                 node_txn.clear();
7397                 txn
7398         };
7399         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7400         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7401         connect_blocks(&nodes[0], 20);
7402         {
7403                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7404                 // We verify than no new transaction has been broadcast because previously
7405                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7406                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7407                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7408                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7409                 // up bumped justice generation.
7410                 assert_eq!(node_txn.len(), 0);
7411                 node_txn.clear();
7412         }
7413         check_closed_broadcast!(nodes[0], true);
7414         check_added_monitors!(nodes[0], 1);
7415 }
7416
7417 #[test]
7418 fn test_bump_penalty_txn_on_remote_commitment() {
7419         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7420         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7421
7422         // Create 2 HTLCs
7423         // Provide preimage for one
7424         // Check aggregation
7425
7426         let chanmon_cfgs = create_chanmon_cfgs(2);
7427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7429         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7430
7431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7432         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7433         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7434
7435         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7436         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7437         assert_eq!(remote_txn[0].output.len(), 4);
7438         assert_eq!(remote_txn[0].input.len(), 1);
7439         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7440
7441         // Claim a HTLC without revocation (provide B monitor with preimage)
7442         nodes[1].node.claim_funds(payment_preimage);
7443         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7444         mine_transaction(&nodes[1], &remote_txn[0]);
7445         check_added_monitors!(nodes[1], 2);
7446         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7447
7448         // One or more claim tx should have been broadcast, check it
7449         let timeout;
7450         let preimage;
7451         let preimage_bump;
7452         let feerate_timeout;
7453         let feerate_preimage;
7454         {
7455                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7456                 // 3 transactions including:
7457                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7458                 assert_eq!(node_txn.len(), 3);
7459                 assert_eq!(node_txn[0].input.len(), 1);
7460                 assert_eq!(node_txn[1].input.len(), 1);
7461                 assert_eq!(node_txn[2].input.len(), 1);
7462                 check_spends!(node_txn[0], remote_txn[0]);
7463                 check_spends!(node_txn[1], remote_txn[0]);
7464                 check_spends!(node_txn[2], remote_txn[0]);
7465
7466                 preimage = node_txn[0].txid();
7467                 let index = node_txn[0].input[0].previous_output.vout;
7468                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7469                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7470
7471                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7472                         (node_txn[2].clone(), node_txn[1].clone())
7473                 } else {
7474                         (node_txn[1].clone(), node_txn[2].clone())
7475                 };
7476
7477                 preimage_bump = preimage_bump_tx;
7478                 check_spends!(preimage_bump, remote_txn[0]);
7479                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7480
7481                 timeout = timeout_tx.txid();
7482                 let index = timeout_tx.input[0].previous_output.vout;
7483                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7484                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7485
7486                 node_txn.clear();
7487         };
7488         assert_ne!(feerate_timeout, 0);
7489         assert_ne!(feerate_preimage, 0);
7490
7491         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7492         connect_blocks(&nodes[1], 1);
7493         {
7494                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7495                 assert_eq!(node_txn.len(), 1);
7496                 assert_eq!(node_txn[0].input.len(), 1);
7497                 assert_eq!(preimage_bump.input.len(), 1);
7498                 check_spends!(node_txn[0], remote_txn[0]);
7499                 check_spends!(preimage_bump, remote_txn[0]);
7500
7501                 let index = preimage_bump.input[0].previous_output.vout;
7502                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7503                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7504                 assert!(new_feerate * 100 > feerate_timeout * 125);
7505                 assert_ne!(timeout, preimage_bump.txid());
7506
7507                 let index = node_txn[0].input[0].previous_output.vout;
7508                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7509                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7510                 assert!(new_feerate * 100 > feerate_preimage * 125);
7511                 assert_ne!(preimage, node_txn[0].txid());
7512
7513                 node_txn.clear();
7514         }
7515
7516         nodes[1].node.get_and_clear_pending_events();
7517         nodes[1].node.get_and_clear_pending_msg_events();
7518 }
7519
7520 #[test]
7521 fn test_counterparty_raa_skip_no_crash() {
7522         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7523         // commitment transaction, we would have happily carried on and provided them the next
7524         // commitment transaction based on one RAA forward. This would probably eventually have led to
7525         // channel closure, but it would not have resulted in funds loss. Still, our
7526         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7527         // check simply that the channel is closed in response to such an RAA, but don't check whether
7528         // we decide to punish our counterparty for revoking their funds (as we don't currently
7529         // implement that).
7530         let chanmon_cfgs = create_chanmon_cfgs(2);
7531         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7532         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7533         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7534         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7535
7536         let per_commitment_secret;
7537         let next_per_commitment_point;
7538         {
7539                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7540                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7541                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7542
7543                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7544
7545                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7546                 keys.get_enforcement_state().last_holder_commitment -= 1;
7547                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7548
7549                 // Must revoke without gaps
7550                 keys.get_enforcement_state().last_holder_commitment -= 1;
7551                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7552
7553                 keys.get_enforcement_state().last_holder_commitment -= 1;
7554                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7555                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7556         }
7557
7558         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7559                 &msgs::RevokeAndACK {
7560                         channel_id,
7561                         per_commitment_secret,
7562                         next_per_commitment_point,
7563                         #[cfg(taproot)]
7564                         next_local_nonce: None,
7565                 });
7566         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7567         check_added_monitors!(nodes[1], 1);
7568         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7569 }
7570
7571 #[test]
7572 fn test_bump_txn_sanitize_tracking_maps() {
7573         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7574         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7575
7576         let chanmon_cfgs = create_chanmon_cfgs(2);
7577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7579         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7580
7581         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7582         // Lock HTLC in both directions
7583         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7584         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7585
7586         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7587         assert_eq!(revoked_local_txn[0].input.len(), 1);
7588         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7589
7590         // Revoke local commitment tx
7591         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7592
7593         // Broadcast set of revoked txn on A
7594         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7595         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7596         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7597
7598         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7599         check_closed_broadcast!(nodes[0], true);
7600         check_added_monitors!(nodes[0], 1);
7601         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7602         let penalty_txn = {
7603                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7604                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7605                 check_spends!(node_txn[0], revoked_local_txn[0]);
7606                 check_spends!(node_txn[1], revoked_local_txn[0]);
7607                 check_spends!(node_txn[2], revoked_local_txn[0]);
7608                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7609                 node_txn.clear();
7610                 penalty_txn
7611         };
7612         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7613         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7614         {
7615                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7616                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7617                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7618         }
7619 }
7620
7621 #[test]
7622 fn test_pending_claimed_htlc_no_balance_underflow() {
7623         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7624         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7625         let chanmon_cfgs = create_chanmon_cfgs(2);
7626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7628         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7629         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7630
7631         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7632         nodes[1].node.claim_funds(payment_preimage);
7633         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7634         check_added_monitors!(nodes[1], 1);
7635         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7636
7637         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7638         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7639         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7640         check_added_monitors!(nodes[0], 1);
7641         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7642
7643         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7644         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7645         // can get our balance.
7646
7647         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7648         // the public key of the only hop. This works around ChannelDetails not showing the
7649         // almost-claimed HTLC as available balance.
7650         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7651         route.payment_params = None; // This is all wrong, but unnecessary
7652         route.paths[0].hops[0].pubkey = nodes[0].node.get_our_node_id();
7653         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7654         nodes[1].node.send_payment_with_route(&route, payment_hash_2,
7655                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7656
7657         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7658 }
7659
7660 #[test]
7661 fn test_channel_conf_timeout() {
7662         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7663         // confirm within 2016 blocks, as recommended by BOLT 2.
7664         let chanmon_cfgs = create_chanmon_cfgs(2);
7665         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7666         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7667         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7668
7669         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7670
7671         // The outbound node should wait forever for confirmation:
7672         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7673         // copied here instead of directly referencing the constant.
7674         connect_blocks(&nodes[0], 2016);
7675         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7676
7677         // The inbound node should fail the channel after exactly 2016 blocks
7678         connect_blocks(&nodes[1], 2015);
7679         check_added_monitors!(nodes[1], 0);
7680         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7681
7682         connect_blocks(&nodes[1], 1);
7683         check_added_monitors!(nodes[1], 1);
7684         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7685         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7686         assert_eq!(close_ev.len(), 1);
7687         match close_ev[0] {
7688                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7689                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7690                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7691                 },
7692                 _ => panic!("Unexpected event"),
7693         }
7694 }
7695
7696 #[test]
7697 fn test_override_channel_config() {
7698         let chanmon_cfgs = create_chanmon_cfgs(2);
7699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7701         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7702
7703         // Node0 initiates a channel to node1 using the override config.
7704         let mut override_config = UserConfig::default();
7705         override_config.channel_handshake_config.our_to_self_delay = 200;
7706
7707         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7708
7709         // Assert the channel created by node0 is using the override config.
7710         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7711         assert_eq!(res.channel_flags, 0);
7712         assert_eq!(res.to_self_delay, 200);
7713 }
7714
7715 #[test]
7716 fn test_override_0msat_htlc_minimum() {
7717         let mut zero_config = UserConfig::default();
7718         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7719         let chanmon_cfgs = create_chanmon_cfgs(2);
7720         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7721         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7722         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7723
7724         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7725         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7726         assert_eq!(res.htlc_minimum_msat, 1);
7727
7728         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7729         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7730         assert_eq!(res.htlc_minimum_msat, 1);
7731 }
7732
7733 #[test]
7734 fn test_channel_update_has_correct_htlc_maximum_msat() {
7735         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7736         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7737         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7738         // 90% of the `channel_value`.
7739         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7740
7741         let mut config_30_percent = UserConfig::default();
7742         config_30_percent.channel_handshake_config.announced_channel = true;
7743         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7744         let mut config_50_percent = UserConfig::default();
7745         config_50_percent.channel_handshake_config.announced_channel = true;
7746         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7747         let mut config_95_percent = UserConfig::default();
7748         config_95_percent.channel_handshake_config.announced_channel = true;
7749         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7750         let mut config_100_percent = UserConfig::default();
7751         config_100_percent.channel_handshake_config.announced_channel = true;
7752         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7753
7754         let chanmon_cfgs = create_chanmon_cfgs(4);
7755         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7756         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)]);
7757         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7758
7759         let channel_value_satoshis = 100000;
7760         let channel_value_msat = channel_value_satoshis * 1000;
7761         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7762         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7763         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7764
7765         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7766         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7767
7768         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7769         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7770         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7771         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7772         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7773         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7774
7775         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7776         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7777         // `channel_value`.
7778         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7779         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7780         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7781         // `channel_value`.
7782         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7783 }
7784
7785 #[test]
7786 fn test_manually_accept_inbound_channel_request() {
7787         let mut manually_accept_conf = UserConfig::default();
7788         manually_accept_conf.manually_accept_inbound_channels = true;
7789         let chanmon_cfgs = create_chanmon_cfgs(2);
7790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7792         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7793
7794         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7795         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7796
7797         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7798
7799         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7800         // accepting the inbound channel request.
7801         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7802
7803         let events = nodes[1].node.get_and_clear_pending_events();
7804         match events[0] {
7805                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7806                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7807                 }
7808                 _ => panic!("Unexpected event"),
7809         }
7810
7811         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7812         assert_eq!(accept_msg_ev.len(), 1);
7813
7814         match accept_msg_ev[0] {
7815                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7816                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7817                 }
7818                 _ => panic!("Unexpected event"),
7819         }
7820
7821         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7822
7823         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7824         assert_eq!(close_msg_ev.len(), 1);
7825
7826         let events = nodes[1].node.get_and_clear_pending_events();
7827         match events[0] {
7828                 Event::ChannelClosed { user_channel_id, .. } => {
7829                         assert_eq!(user_channel_id, 23);
7830                 }
7831                 _ => panic!("Unexpected event"),
7832         }
7833 }
7834
7835 #[test]
7836 fn test_manually_reject_inbound_channel_request() {
7837         let mut manually_accept_conf = UserConfig::default();
7838         manually_accept_conf.manually_accept_inbound_channels = true;
7839         let chanmon_cfgs = create_chanmon_cfgs(2);
7840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7842         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7843
7844         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7845         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7846
7847         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7848
7849         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7850         // rejecting the inbound channel request.
7851         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7852
7853         let events = nodes[1].node.get_and_clear_pending_events();
7854         match events[0] {
7855                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7856                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7857                 }
7858                 _ => panic!("Unexpected event"),
7859         }
7860
7861         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7862         assert_eq!(close_msg_ev.len(), 1);
7863
7864         match close_msg_ev[0] {
7865                 MessageSendEvent::HandleError { ref node_id, .. } => {
7866                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7867                 }
7868                 _ => panic!("Unexpected event"),
7869         }
7870         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7871 }
7872
7873 #[test]
7874 fn test_reject_funding_before_inbound_channel_accepted() {
7875         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7876         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7877         // the node operator before the counterparty sends a `FundingCreated` message. If a
7878         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7879         // and the channel should be closed.
7880         let mut manually_accept_conf = UserConfig::default();
7881         manually_accept_conf.manually_accept_inbound_channels = true;
7882         let chanmon_cfgs = create_chanmon_cfgs(2);
7883         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7884         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7885         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7886
7887         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7888         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7889         let temp_channel_id = res.temporary_channel_id;
7890
7891         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7892
7893         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7894         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7895
7896         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7897         nodes[1].node.get_and_clear_pending_events();
7898
7899         // Get the `AcceptChannel` message of `nodes[1]` without calling
7900         // `ChannelManager::accept_inbound_channel`, which generates a
7901         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7902         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7903         // succeed when `nodes[0]` is passed to it.
7904         let accept_chan_msg = {
7905                 let mut node_1_per_peer_lock;
7906                 let mut node_1_peer_state_lock;
7907                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7908                 channel.get_accept_channel_message()
7909         };
7910         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7911
7912         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7913
7914         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7915         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7916
7917         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7918         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7919
7920         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7921         assert_eq!(close_msg_ev.len(), 1);
7922
7923         let expected_err = "FundingCreated message received before the channel was accepted";
7924         match close_msg_ev[0] {
7925                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7926                         assert_eq!(msg.channel_id, temp_channel_id);
7927                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7928                         assert_eq!(msg.data, expected_err);
7929                 }
7930                 _ => panic!("Unexpected event"),
7931         }
7932
7933         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7934 }
7935
7936 #[test]
7937 fn test_can_not_accept_inbound_channel_twice() {
7938         let mut manually_accept_conf = UserConfig::default();
7939         manually_accept_conf.manually_accept_inbound_channels = true;
7940         let chanmon_cfgs = create_chanmon_cfgs(2);
7941         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7942         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7943         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7944
7945         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7946         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7947
7948         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7949
7950         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7951         // accepting the inbound channel request.
7952         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7953
7954         let events = nodes[1].node.get_and_clear_pending_events();
7955         match events[0] {
7956                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7957                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7958                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7959                         match api_res {
7960                                 Err(APIError::APIMisuseError { err }) => {
7961                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7962                                 },
7963                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7964                                 Err(_) => panic!("Unexpected Error"),
7965                         }
7966                 }
7967                 _ => panic!("Unexpected event"),
7968         }
7969
7970         // Ensure that the channel wasn't closed after attempting to accept it twice.
7971         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7972         assert_eq!(accept_msg_ev.len(), 1);
7973
7974         match accept_msg_ev[0] {
7975                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7976                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7977                 }
7978                 _ => panic!("Unexpected event"),
7979         }
7980 }
7981
7982 #[test]
7983 fn test_can_not_accept_unknown_inbound_channel() {
7984         let chanmon_cfg = create_chanmon_cfgs(2);
7985         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7986         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7987         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7988
7989         let unknown_channel_id = [0; 32];
7990         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7991         match api_res {
7992                 Err(APIError::ChannelUnavailable { err }) => {
7993                         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()));
7994                 },
7995                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7996                 Err(_) => panic!("Unexpected Error"),
7997         }
7998 }
7999
8000 #[test]
8001 fn test_onion_value_mpp_set_calculation() {
8002         // Test that we use the onion value `amt_to_forward` when
8003         // calculating whether we've reached the `total_msat` of an MPP
8004         // by having a routing node forward more than `amt_to_forward`
8005         // and checking that the receiving node doesn't generate
8006         // a PaymentClaimable event too early
8007         let node_count = 4;
8008         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8009         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8010         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8011         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8012
8013         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8014         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8015         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8016         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8017
8018         let total_msat = 100_000;
8019         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8020         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8021         let sample_path = route.paths.pop().unwrap();
8022
8023         let mut path_1 = sample_path.clone();
8024         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8025         path_1.hops[0].short_channel_id = chan_1_id;
8026         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8027         path_1.hops[1].short_channel_id = chan_3_id;
8028         path_1.hops[1].fee_msat = 100_000;
8029         route.paths.push(path_1);
8030
8031         let mut path_2 = sample_path.clone();
8032         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8033         path_2.hops[0].short_channel_id = chan_2_id;
8034         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8035         path_2.hops[1].short_channel_id = chan_4_id;
8036         path_2.hops[1].fee_msat = 1_000;
8037         route.paths.push(path_2);
8038
8039         // Send payment
8040         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8041         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8042                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8043         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8044                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8045         check_added_monitors!(nodes[0], expected_paths.len());
8046
8047         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8048         assert_eq!(events.len(), expected_paths.len());
8049
8050         // First path
8051         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8052         let mut payment_event = SendEvent::from_event(ev);
8053         let mut prev_node = &nodes[0];
8054
8055         for (idx, &node) in expected_paths[0].iter().enumerate() {
8056                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8057
8058                 if idx == 0 { // routing node
8059                         let session_priv = [3; 32];
8060                         let height = nodes[0].best_block_info().1;
8061                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8062                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8063                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8064                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8065                         // Edit amt_to_forward to simulate the sender having set
8066                         // the final amount and the routing node taking less fee
8067                         onion_payloads[1].amt_to_forward = 99_000;
8068                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8069                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8070                 }
8071
8072                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8073                 check_added_monitors!(node, 0);
8074                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8075                 expect_pending_htlcs_forwardable!(node);
8076
8077                 if idx == 0 {
8078                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8079                         assert_eq!(events_2.len(), 1);
8080                         check_added_monitors!(node, 1);
8081                         payment_event = SendEvent::from_event(events_2.remove(0));
8082                         assert_eq!(payment_event.msgs.len(), 1);
8083                 } else {
8084                         let events_2 = node.node.get_and_clear_pending_events();
8085                         assert!(events_2.is_empty());
8086                 }
8087
8088                 prev_node = node;
8089         }
8090
8091         // Second path
8092         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8093         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8094
8095         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8096 }
8097
8098 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8099
8100         let routing_node_count = msat_amounts.len();
8101         let node_count = routing_node_count + 2;
8102
8103         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8104         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8105         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8106         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8107
8108         let src_idx = 0;
8109         let dst_idx = 1;
8110
8111         // Create channels for each amount
8112         let mut expected_paths = Vec::with_capacity(routing_node_count);
8113         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8114         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8115         for i in 0..routing_node_count {
8116                 let routing_node = 2 + i;
8117                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8118                 src_chan_ids.push(src_chan_id);
8119                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8120                 dst_chan_ids.push(dst_chan_id);
8121                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8122                 expected_paths.push(path);
8123         }
8124         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8125
8126         // Create a route for each amount
8127         let example_amount = 100000;
8128         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);
8129         let sample_path = route.paths.pop().unwrap();
8130         for i in 0..routing_node_count {
8131                 let routing_node = 2 + i;
8132                 let mut path = sample_path.clone();
8133                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8134                 path.hops[0].short_channel_id = src_chan_ids[i];
8135                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8136                 path.hops[1].short_channel_id = dst_chan_ids[i];
8137                 path.hops[1].fee_msat = msat_amounts[i];
8138                 route.paths.push(path);
8139         }
8140
8141         // Send payment with manually set total_msat
8142         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8143         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8144                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8145         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8146                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8147         check_added_monitors!(nodes[src_idx], expected_paths.len());
8148
8149         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8150         assert_eq!(events.len(), expected_paths.len());
8151         let mut amount_received = 0;
8152         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8153                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8154
8155                 let current_path_amount = msat_amounts[path_idx];
8156                 amount_received += current_path_amount;
8157                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8158                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8159         }
8160
8161         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8162 }
8163
8164 #[test]
8165 fn test_overshoot_mpp() {
8166         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8167         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8168 }
8169
8170 #[test]
8171 fn test_simple_mpp() {
8172         // Simple test of sending a multi-path payment.
8173         let chanmon_cfgs = create_chanmon_cfgs(4);
8174         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8175         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8176         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8177
8178         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8179         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8180         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8181         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8182
8183         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8184         let path = route.paths[0].clone();
8185         route.paths.push(path);
8186         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8187         route.paths[0].hops[0].short_channel_id = chan_1_id;
8188         route.paths[0].hops[1].short_channel_id = chan_3_id;
8189         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8190         route.paths[1].hops[0].short_channel_id = chan_2_id;
8191         route.paths[1].hops[1].short_channel_id = chan_4_id;
8192         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8193         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8194 }
8195
8196 #[test]
8197 fn test_preimage_storage() {
8198         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8199         let chanmon_cfgs = create_chanmon_cfgs(2);
8200         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8201         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8202         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8203
8204         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8205
8206         {
8207                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8208                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8209                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8210                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8211                 check_added_monitors!(nodes[0], 1);
8212                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8213                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8214                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8215                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8216         }
8217         // Note that after leaving the above scope we have no knowledge of any arguments or return
8218         // values from previous calls.
8219         expect_pending_htlcs_forwardable!(nodes[1]);
8220         let events = nodes[1].node.get_and_clear_pending_events();
8221         assert_eq!(events.len(), 1);
8222         match events[0] {
8223                 Event::PaymentClaimable { ref purpose, .. } => {
8224                         match &purpose {
8225                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8226                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8227                                 },
8228                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8229                         }
8230                 },
8231                 _ => panic!("Unexpected event"),
8232         }
8233 }
8234
8235 #[test]
8236 #[allow(deprecated)]
8237 fn test_secret_timeout() {
8238         // Simple test of payment secret storage time outs. After
8239         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8240         let chanmon_cfgs = create_chanmon_cfgs(2);
8241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8243         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8244
8245         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8246
8247         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8248
8249         // We should fail to register the same payment hash twice, at least until we've connected a
8250         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8251         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8252                 assert_eq!(err, "Duplicate payment hash");
8253         } else { panic!(); }
8254         let mut block = {
8255                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8256                 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8257         };
8258         connect_block(&nodes[1], &block);
8259         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8260                 assert_eq!(err, "Duplicate payment hash");
8261         } else { panic!(); }
8262
8263         // If we then connect the second block, we should be able to register the same payment hash
8264         // again (this time getting a new payment secret).
8265         block.header.prev_blockhash = block.header.block_hash();
8266         block.header.time += 1;
8267         connect_block(&nodes[1], &block);
8268         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8269         assert_ne!(payment_secret_1, our_payment_secret);
8270
8271         {
8272                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8273                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8274                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8275                 check_added_monitors!(nodes[0], 1);
8276                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8277                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8278                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8279                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8280         }
8281         // Note that after leaving the above scope we have no knowledge of any arguments or return
8282         // values from previous calls.
8283         expect_pending_htlcs_forwardable!(nodes[1]);
8284         let events = nodes[1].node.get_and_clear_pending_events();
8285         assert_eq!(events.len(), 1);
8286         match events[0] {
8287                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8288                         assert!(payment_preimage.is_none());
8289                         assert_eq!(payment_secret, our_payment_secret);
8290                         // We don't actually have the payment preimage with which to claim this payment!
8291                 },
8292                 _ => panic!("Unexpected event"),
8293         }
8294 }
8295
8296 #[test]
8297 fn test_bad_secret_hash() {
8298         // Simple test of unregistered payment hash/invalid payment secret handling
8299         let chanmon_cfgs = create_chanmon_cfgs(2);
8300         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8301         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8302         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8303
8304         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8305
8306         let random_payment_hash = PaymentHash([42; 32]);
8307         let random_payment_secret = PaymentSecret([43; 32]);
8308         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8309         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8310
8311         // All the below cases should end up being handled exactly identically, so we macro the
8312         // resulting events.
8313         macro_rules! handle_unknown_invalid_payment_data {
8314                 ($payment_hash: expr) => {
8315                         check_added_monitors!(nodes[0], 1);
8316                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8317                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8318                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8319                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8320
8321                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8322                         // again to process the pending backwards-failure of the HTLC
8323                         expect_pending_htlcs_forwardable!(nodes[1]);
8324                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8325                         check_added_monitors!(nodes[1], 1);
8326
8327                         // We should fail the payment back
8328                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8329                         match events.pop().unwrap() {
8330                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8331                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8332                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8333                                 },
8334                                 _ => panic!("Unexpected event"),
8335                         }
8336                 }
8337         }
8338
8339         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8340         // Error data is the HTLC value (100,000) and current block height
8341         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8342
8343         // Send a payment with the right payment hash but the wrong payment secret
8344         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8345                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8346         handle_unknown_invalid_payment_data!(our_payment_hash);
8347         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8348
8349         // Send a payment with a random payment hash, but the right payment secret
8350         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8351                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8352         handle_unknown_invalid_payment_data!(random_payment_hash);
8353         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8354
8355         // Send a payment with a random payment hash and random payment secret
8356         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8357                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8358         handle_unknown_invalid_payment_data!(random_payment_hash);
8359         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8360 }
8361
8362 #[test]
8363 fn test_update_err_monitor_lockdown() {
8364         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8365         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8366         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8367         // error.
8368         //
8369         // This scenario may happen in a watchtower setup, where watchtower process a block height
8370         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8371         // commitment at same time.
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         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8387
8388         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8389         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8390         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8391         let persister = test_utils::TestPersister::new();
8392         let watchtower = {
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 block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8405         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8406         // transaction lock time requirements here.
8407         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8408         watchtower.chain_monitor.block_connected(&block, 200);
8409
8410         // Try to update ChannelMonitor
8411         nodes[1].node.claim_funds(preimage);
8412         check_added_monitors!(nodes[1], 1);
8413         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8414
8415         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8416         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8417         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8418         {
8419                 let mut node_0_per_peer_lock;
8420                 let mut node_0_peer_state_lock;
8421                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8422                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8423                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8424                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8425                 } else { assert!(false); }
8426         }
8427         // Our local monitor is in-sync and hasn't processed yet timeout
8428         check_added_monitors!(nodes[0], 1);
8429         let events = nodes[0].node.get_and_clear_pending_events();
8430         assert_eq!(events.len(), 1);
8431 }
8432
8433 #[test]
8434 fn test_concurrent_monitor_claim() {
8435         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8436         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8437         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8438         // state N+1 confirms. Alice claims output from state N+1.
8439
8440         let chanmon_cfgs = create_chanmon_cfgs(2);
8441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8443         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8444
8445         // Create some initial channel
8446         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8447         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8448
8449         // Rebalance the network to generate htlc in the two directions
8450         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8451
8452         // Route a HTLC from node 0 to node 1 (but don't settle)
8453         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8454
8455         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8456         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8457         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8458         let persister = test_utils::TestPersister::new();
8459         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8460                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8461         );
8462         let watchtower_alice = {
8463                 let new_monitor = {
8464                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8465                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8466                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8467                         assert!(new_monitor == *monitor);
8468                         new_monitor
8469                 };
8470                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8471                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8472                 watchtower
8473         };
8474         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8475         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8476         // requirements here.
8477         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8478         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8479         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8480
8481         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8482         let alice_state = {
8483                 let mut txn = alice_broadcaster.txn_broadcast();
8484                 assert_eq!(txn.len(), 2);
8485                 txn.remove(0)
8486         };
8487
8488         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8489         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8490         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8491         let persister = test_utils::TestPersister::new();
8492         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8493         let watchtower_bob = {
8494                 let new_monitor = {
8495                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8496                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8497                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8498                         assert!(new_monitor == *monitor);
8499                         new_monitor
8500                 };
8501                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8502                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8503                 watchtower
8504         };
8505         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8506
8507         // Route another payment to generate another update with still previous HTLC pending
8508         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8509         nodes[1].node.send_payment_with_route(&route, payment_hash,
8510                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8511         check_added_monitors!(nodes[1], 1);
8512
8513         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8514         assert_eq!(updates.update_add_htlcs.len(), 1);
8515         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8516         {
8517                 let mut node_0_per_peer_lock;
8518                 let mut node_0_peer_state_lock;
8519                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8520                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8521                         // Watchtower Alice should already have seen the block and reject the update
8522                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8523                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8524                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8525                 } else { assert!(false); }
8526         }
8527         // Our local monitor is in-sync and hasn't processed yet timeout
8528         check_added_monitors!(nodes[0], 1);
8529
8530         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8531         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8532
8533         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8534         let bob_state_y;
8535         {
8536                 let mut txn = bob_broadcaster.txn_broadcast();
8537                 assert_eq!(txn.len(), 2);
8538                 bob_state_y = txn.remove(0);
8539         };
8540
8541         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8542         let height = HTLC_TIMEOUT_BROADCAST + 1;
8543         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8544         check_closed_broadcast(&nodes[0], 1, true);
8545         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8546         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8547         check_added_monitors(&nodes[0], 1);
8548         {
8549                 let htlc_txn = alice_broadcaster.txn_broadcast();
8550                 assert_eq!(htlc_txn.len(), 2);
8551                 check_spends!(htlc_txn[0], bob_state_y);
8552                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8553                 // it. However, she should, because it now has an invalid parent.
8554                 check_spends!(htlc_txn[1], alice_state);
8555         }
8556 }
8557
8558 #[test]
8559 fn test_pre_lockin_no_chan_closed_update() {
8560         // Test that if a peer closes a channel in response to a funding_created message we don't
8561         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8562         // message).
8563         //
8564         // Doing so would imply a channel monitor update before the initial channel monitor
8565         // registration, violating our API guarantees.
8566         //
8567         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8568         // then opening a second channel with the same funding output as the first (which is not
8569         // rejected because the first channel does not exist in the ChannelManager) and closing it
8570         // before receiving funding_signed.
8571         let chanmon_cfgs = create_chanmon_cfgs(2);
8572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8574         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8575
8576         // Create an initial channel
8577         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8578         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8579         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8580         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8581         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8582
8583         // Move the first channel through the funding flow...
8584         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8585
8586         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8587         check_added_monitors!(nodes[0], 0);
8588
8589         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8590         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8591         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8592         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8593         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8594 }
8595
8596 #[test]
8597 fn test_htlc_no_detection() {
8598         // This test is a mutation to underscore the detection logic bug we had
8599         // before #653. HTLC value routed is above the remaining balance, thus
8600         // inverting HTLC and `to_remote` output. HTLC will come second and
8601         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8602         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8603         // outputs order detection for correct spending children filtring.
8604
8605         let chanmon_cfgs = create_chanmon_cfgs(2);
8606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8609
8610         // Create some initial channels
8611         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8612
8613         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8614         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8615         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8616         assert_eq!(local_txn[0].input.len(), 1);
8617         assert_eq!(local_txn[0].output.len(), 3);
8618         check_spends!(local_txn[0], chan_1.3);
8619
8620         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8621         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8622         connect_block(&nodes[0], &block);
8623         // We deliberately connect the local tx twice as this should provoke a failure calling
8624         // this test before #653 fix.
8625         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8626         check_closed_broadcast!(nodes[0], true);
8627         check_added_monitors!(nodes[0], 1);
8628         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8629         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8630
8631         let htlc_timeout = {
8632                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8633                 assert_eq!(node_txn.len(), 1);
8634                 assert_eq!(node_txn[0].input.len(), 1);
8635                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8636                 check_spends!(node_txn[0], local_txn[0]);
8637                 node_txn[0].clone()
8638         };
8639
8640         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8641         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8642         expect_payment_failed!(nodes[0], our_payment_hash, false);
8643 }
8644
8645 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8646         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8647         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8648         // Carol, Alice would be the upstream node, and Carol the downstream.)
8649         //
8650         // Steps of the test:
8651         // 1) Alice sends a HTLC to Carol through Bob.
8652         // 2) Carol doesn't settle the HTLC.
8653         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8654         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8655         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8656         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8657         // 5) Carol release the preimage to Bob off-chain.
8658         // 6) Bob claims the offered output on the broadcasted commitment.
8659         let chanmon_cfgs = create_chanmon_cfgs(3);
8660         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8661         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8662         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8663
8664         // Create some initial channels
8665         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8666         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8667
8668         // Steps (1) and (2):
8669         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8670         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8671
8672         // Check that Alice's commitment transaction now contains an output for this HTLC.
8673         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8674         check_spends!(alice_txn[0], chan_ab.3);
8675         assert_eq!(alice_txn[0].output.len(), 2);
8676         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8677         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8678         assert_eq!(alice_txn.len(), 2);
8679
8680         // Steps (3) and (4):
8681         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8682         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8683         let mut force_closing_node = 0; // Alice force-closes
8684         let mut counterparty_node = 1; // Bob if Alice force-closes
8685
8686         // Bob force-closes
8687         if !broadcast_alice {
8688                 force_closing_node = 1;
8689                 counterparty_node = 0;
8690         }
8691         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8692         check_closed_broadcast!(nodes[force_closing_node], true);
8693         check_added_monitors!(nodes[force_closing_node], 1);
8694         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8695         if go_onchain_before_fulfill {
8696                 let txn_to_broadcast = match broadcast_alice {
8697                         true => alice_txn.clone(),
8698                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8699                 };
8700                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8701                 if broadcast_alice {
8702                         check_closed_broadcast!(nodes[1], true);
8703                         check_added_monitors!(nodes[1], 1);
8704                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8705                 }
8706         }
8707
8708         // Step (5):
8709         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8710         // process of removing the HTLC from their commitment transactions.
8711         nodes[2].node.claim_funds(payment_preimage);
8712         check_added_monitors!(nodes[2], 1);
8713         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8714
8715         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8716         assert!(carol_updates.update_add_htlcs.is_empty());
8717         assert!(carol_updates.update_fail_htlcs.is_empty());
8718         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8719         assert!(carol_updates.update_fee.is_none());
8720         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8721
8722         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8723         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8724         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8725         if !go_onchain_before_fulfill && broadcast_alice {
8726                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8727                 assert_eq!(events.len(), 1);
8728                 match events[0] {
8729                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8730                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8731                         },
8732                         _ => panic!("Unexpected event"),
8733                 };
8734         }
8735         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8736         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8737         // Carol<->Bob's updated commitment transaction info.
8738         check_added_monitors!(nodes[1], 2);
8739
8740         let events = nodes[1].node.get_and_clear_pending_msg_events();
8741         assert_eq!(events.len(), 2);
8742         let bob_revocation = match events[0] {
8743                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8744                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8745                         (*msg).clone()
8746                 },
8747                 _ => panic!("Unexpected event"),
8748         };
8749         let bob_updates = match events[1] {
8750                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8751                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8752                         (*updates).clone()
8753                 },
8754                 _ => panic!("Unexpected event"),
8755         };
8756
8757         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8758         check_added_monitors!(nodes[2], 1);
8759         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8760         check_added_monitors!(nodes[2], 1);
8761
8762         let events = nodes[2].node.get_and_clear_pending_msg_events();
8763         assert_eq!(events.len(), 1);
8764         let carol_revocation = match events[0] {
8765                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8766                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8767                         (*msg).clone()
8768                 },
8769                 _ => panic!("Unexpected event"),
8770         };
8771         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8772         check_added_monitors!(nodes[1], 1);
8773
8774         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8775         // here's where we put said channel's commitment tx on-chain.
8776         let mut txn_to_broadcast = alice_txn.clone();
8777         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8778         if !go_onchain_before_fulfill {
8779                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8780                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8781                 if broadcast_alice {
8782                         check_closed_broadcast!(nodes[1], true);
8783                         check_added_monitors!(nodes[1], 1);
8784                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8785                 }
8786                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8787                 if broadcast_alice {
8788                         assert_eq!(bob_txn.len(), 1);
8789                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8790                 } else {
8791                         assert_eq!(bob_txn.len(), 2);
8792                         check_spends!(bob_txn[0], chan_ab.3);
8793                 }
8794         }
8795
8796         // Step (6):
8797         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8798         // broadcasted commitment transaction.
8799         {
8800                 let script_weight = match broadcast_alice {
8801                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8802                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8803                 };
8804                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8805                 // Bob force-closed and broadcasts the commitment transaction along with a
8806                 // HTLC-output-claiming transaction.
8807                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8808                 if broadcast_alice {
8809                         assert_eq!(bob_txn.len(), 1);
8810                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8811                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8812                 } else {
8813                         assert_eq!(bob_txn.len(), 2);
8814                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8815                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8816                 }
8817         }
8818 }
8819
8820 #[test]
8821 fn test_onchain_htlc_settlement_after_close() {
8822         do_test_onchain_htlc_settlement_after_close(true, true);
8823         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8824         do_test_onchain_htlc_settlement_after_close(true, false);
8825         do_test_onchain_htlc_settlement_after_close(false, false);
8826 }
8827
8828 #[test]
8829 fn test_duplicate_temporary_channel_id_from_different_peers() {
8830         // Tests that we can accept two different `OpenChannel` requests with the same
8831         // `temporary_channel_id`, as long as they are from different peers.
8832         let chanmon_cfgs = create_chanmon_cfgs(3);
8833         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8834         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8835         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8836
8837         // Create an first channel channel
8838         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8839         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8840
8841         // Create an second channel
8842         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8843         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8844
8845         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8846         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8847         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8848
8849         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8850         // `temporary_channel_id` as they are from different peers.
8851         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8852         {
8853                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8854                 assert_eq!(events.len(), 1);
8855                 match &events[0] {
8856                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8857                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8858                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8859                         },
8860                         _ => panic!("Unexpected event"),
8861                 }
8862         }
8863
8864         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8865         {
8866                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8867                 assert_eq!(events.len(), 1);
8868                 match &events[0] {
8869                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8870                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8871                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8872                         },
8873                         _ => panic!("Unexpected event"),
8874                 }
8875         }
8876 }
8877
8878 #[test]
8879 fn test_duplicate_chan_id() {
8880         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8881         // already open we reject it and keep the old channel.
8882         //
8883         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8884         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8885         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8886         // updating logic for the existing channel.
8887         let chanmon_cfgs = create_chanmon_cfgs(2);
8888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8890         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8891
8892         // Create an initial channel
8893         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8894         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8895         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8896         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()));
8897
8898         // Try to create a second channel with the same temporary_channel_id as the first and check
8899         // that it is rejected.
8900         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8901         {
8902                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8903                 assert_eq!(events.len(), 1);
8904                 match events[0] {
8905                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8906                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8907                                 // first (valid) and second (invalid) channels are closed, given they both have
8908                                 // the same non-temporary channel_id. However, currently we do not, so we just
8909                                 // move forward with it.
8910                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8911                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8912                         },
8913                         _ => panic!("Unexpected event"),
8914                 }
8915         }
8916
8917         // Move the first channel through the funding flow...
8918         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8919
8920         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8921         check_added_monitors!(nodes[0], 0);
8922
8923         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8924         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8925         {
8926                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8927                 assert_eq!(added_monitors.len(), 1);
8928                 assert_eq!(added_monitors[0].0, funding_output);
8929                 added_monitors.clear();
8930         }
8931         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8932
8933         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8934
8935         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8936         let channel_id = funding_outpoint.to_channel_id();
8937
8938         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8939         // temporary one).
8940
8941         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8942         // Technically this is allowed by the spec, but we don't support it and there's little reason
8943         // to. Still, it shouldn't cause any other issues.
8944         open_chan_msg.temporary_channel_id = channel_id;
8945         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8946         {
8947                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8948                 assert_eq!(events.len(), 1);
8949                 match events[0] {
8950                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8951                                 // Technically, at this point, nodes[1] would be justified in thinking both
8952                                 // channels are closed, but currently we do not, so we just move forward with it.
8953                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8954                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8955                         },
8956                         _ => panic!("Unexpected event"),
8957                 }
8958         }
8959
8960         // Now try to create a second channel which has a duplicate funding output.
8961         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8962         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8963         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8964         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()));
8965         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8966
8967         let funding_created = {
8968                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8969                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8970                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8971                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8972                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8973                 // channelmanager in a possibly nonsense state instead).
8974                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8975                 let logger = test_utils::TestLogger::new();
8976                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8977         };
8978         check_added_monitors!(nodes[0], 0);
8979         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8980         // At this point we'll look up if the channel_id is present and immediately fail the channel
8981         // without trying to persist the `ChannelMonitor`.
8982         check_added_monitors!(nodes[1], 0);
8983
8984         // ...still, nodes[1] will reject the duplicate channel.
8985         {
8986                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8987                 assert_eq!(events.len(), 1);
8988                 match events[0] {
8989                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8990                                 // Technically, at this point, nodes[1] would be justified in thinking both
8991                                 // channels are closed, but currently we do not, so we just move forward with it.
8992                                 assert_eq!(msg.channel_id, channel_id);
8993                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8994                         },
8995                         _ => panic!("Unexpected event"),
8996                 }
8997         }
8998
8999         // finally, finish creating the original channel and send a payment over it to make sure
9000         // everything is functional.
9001         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9002         {
9003                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9004                 assert_eq!(added_monitors.len(), 1);
9005                 assert_eq!(added_monitors[0].0, funding_output);
9006                 added_monitors.clear();
9007         }
9008         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9009
9010         let events_4 = nodes[0].node.get_and_clear_pending_events();
9011         assert_eq!(events_4.len(), 0);
9012         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9013         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9014
9015         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9016         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9017         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9018
9019         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9020 }
9021
9022 #[test]
9023 fn test_error_chans_closed() {
9024         // Test that we properly handle error messages, closing appropriate channels.
9025         //
9026         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9027         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9028         // we can test various edge cases around it to ensure we don't regress.
9029         let chanmon_cfgs = create_chanmon_cfgs(3);
9030         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9031         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9032         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9033
9034         // Create some initial channels
9035         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9036         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9037         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9038
9039         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9040         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9041         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9042
9043         // Closing a channel from a different peer has no effect
9044         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9045         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9046
9047         // Closing one channel doesn't impact others
9048         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9049         check_added_monitors!(nodes[0], 1);
9050         check_closed_broadcast!(nodes[0], false);
9051         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9052         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9053         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9054         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);
9055         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);
9056
9057         // A null channel ID should close all channels
9058         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9059         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9060         check_added_monitors!(nodes[0], 2);
9061         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9062         let events = nodes[0].node.get_and_clear_pending_msg_events();
9063         assert_eq!(events.len(), 2);
9064         match events[0] {
9065                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9066                         assert_eq!(msg.contents.flags & 2, 2);
9067                 },
9068                 _ => panic!("Unexpected event"),
9069         }
9070         match events[1] {
9071                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9072                         assert_eq!(msg.contents.flags & 2, 2);
9073                 },
9074                 _ => panic!("Unexpected event"),
9075         }
9076         // Note that at this point users of a standard PeerHandler will end up calling
9077         // peer_disconnected.
9078         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9079         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9080
9081         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9082         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9083         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9084 }
9085
9086 #[test]
9087 fn test_invalid_funding_tx() {
9088         // Test that we properly handle invalid funding transactions sent to us from a peer.
9089         //
9090         // Previously, all other major lightning implementations had failed to properly sanitize
9091         // funding transactions from their counterparties, leading to a multi-implementation critical
9092         // security vulnerability (though we always sanitized properly, we've previously had
9093         // un-released crashes in the sanitization process).
9094         //
9095         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9096         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9097         // gave up on it. We test this here by generating such a transaction.
9098         let chanmon_cfgs = create_chanmon_cfgs(2);
9099         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9100         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9101         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9102
9103         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9104         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()));
9105         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()));
9106
9107         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9108
9109         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9110         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9111         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9112         // its length.
9113         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9114         let wit_program_script: Script = wit_program.into();
9115         for output in tx.output.iter_mut() {
9116                 // Make the confirmed funding transaction have a bogus script_pubkey
9117                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9118         }
9119
9120         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9121         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()));
9122         check_added_monitors!(nodes[1], 1);
9123         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9124
9125         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()));
9126         check_added_monitors!(nodes[0], 1);
9127         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9128
9129         let events_1 = nodes[0].node.get_and_clear_pending_events();
9130         assert_eq!(events_1.len(), 0);
9131
9132         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9133         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9134         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9135
9136         let expected_err = "funding tx had wrong script/value or output index";
9137         confirm_transaction_at(&nodes[1], &tx, 1);
9138         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9139         check_added_monitors!(nodes[1], 1);
9140         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9141         assert_eq!(events_2.len(), 1);
9142         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9143                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9144                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9145                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9146                 } else { panic!(); }
9147         } else { panic!(); }
9148         assert_eq!(nodes[1].node.list_channels().len(), 0);
9149
9150         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9151         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9152         // as its not 32 bytes long.
9153         let mut spend_tx = Transaction {
9154                 version: 2i32, lock_time: PackedLockTime::ZERO,
9155                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9156                         previous_output: BitcoinOutPoint {
9157                                 txid: tx.txid(),
9158                                 vout: idx as u32,
9159                         },
9160                         script_sig: Script::new(),
9161                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9162                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9163                 }).collect(),
9164                 output: vec![TxOut {
9165                         value: 1000,
9166                         script_pubkey: Script::new(),
9167                 }]
9168         };
9169         check_spends!(spend_tx, tx);
9170         mine_transaction(&nodes[1], &spend_tx);
9171 }
9172
9173 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9174         // In the first version of the chain::Confirm interface, after a refactor was made to not
9175         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9176         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9177         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9178         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9179         // spending transaction until height N+1 (or greater). This was due to the way
9180         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9181         // spending transaction at the height the input transaction was confirmed at, not whether we
9182         // should broadcast a spending transaction at the current height.
9183         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9184         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9185         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9186         // until we learned about an additional block.
9187         //
9188         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9189         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9190         let chanmon_cfgs = create_chanmon_cfgs(3);
9191         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9192         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9193         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9194         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9195
9196         create_announced_chan_between_nodes(&nodes, 0, 1);
9197         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9198         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9199         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9200         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9201
9202         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9203         check_closed_broadcast!(nodes[1], true);
9204         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9205         check_added_monitors!(nodes[1], 1);
9206         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9207         assert_eq!(node_txn.len(), 1);
9208
9209         let conf_height = nodes[1].best_block_info().1;
9210         if !test_height_before_timelock {
9211                 connect_blocks(&nodes[1], 24 * 6);
9212         }
9213         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9214                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9215         if test_height_before_timelock {
9216                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9217                 // generate any events or broadcast any transactions
9218                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9219                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9220         } else {
9221                 // We should broadcast an HTLC transaction spending our funding transaction first
9222                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9223                 assert_eq!(spending_txn.len(), 2);
9224                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9225                 check_spends!(spending_txn[1], node_txn[0]);
9226                 // We should also generate a SpendableOutputs event with the to_self output (as its
9227                 // timelock is up).
9228                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9229                 assert_eq!(descriptor_spend_txn.len(), 1);
9230
9231                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9232                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9233                 // additional block built on top of the current chain.
9234                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9235                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9236                 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 }]);
9237                 check_added_monitors!(nodes[1], 1);
9238
9239                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9240                 assert!(updates.update_add_htlcs.is_empty());
9241                 assert!(updates.update_fulfill_htlcs.is_empty());
9242                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9243                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9244                 assert!(updates.update_fee.is_none());
9245                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9246                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9247                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9248         }
9249 }
9250
9251 #[test]
9252 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9253         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9254         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9255 }
9256
9257 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9258         let chanmon_cfgs = create_chanmon_cfgs(2);
9259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9261         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9262
9263         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9264
9265         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9266                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9267         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9268
9269         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9270
9271         {
9272                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9273                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9274                 check_added_monitors!(nodes[0], 1);
9275                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9276                 assert_eq!(events.len(), 1);
9277                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9278                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9279                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9280         }
9281         expect_pending_htlcs_forwardable!(nodes[1]);
9282         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9283
9284         {
9285                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9286                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9287                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9288                 check_added_monitors!(nodes[0], 1);
9289                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9290                 assert_eq!(events.len(), 1);
9291                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9292                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9293                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9294                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9295                 // assume the second is a privacy attack (no longer particularly relevant
9296                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9297                 // the first HTLC delivered above.
9298         }
9299
9300         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9301         nodes[1].node.process_pending_htlc_forwards();
9302
9303         if test_for_second_fail_panic {
9304                 // Now we go fail back the first HTLC from the user end.
9305                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9306
9307                 let expected_destinations = vec![
9308                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9309                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9310                 ];
9311                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9312                 nodes[1].node.process_pending_htlc_forwards();
9313
9314                 check_added_monitors!(nodes[1], 1);
9315                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9316                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9317
9318                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9319                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9320                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9321
9322                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9323                 assert_eq!(failure_events.len(), 4);
9324                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9325                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9326                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9327                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9328         } else {
9329                 // Let the second HTLC fail and claim the first
9330                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9331                 nodes[1].node.process_pending_htlc_forwards();
9332
9333                 check_added_monitors!(nodes[1], 1);
9334                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9335                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9336                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9337
9338                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9339
9340                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9341         }
9342 }
9343
9344 #[test]
9345 fn test_dup_htlc_second_fail_panic() {
9346         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9347         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9348         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9349         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9350         do_test_dup_htlc_second_rejected(true);
9351 }
9352
9353 #[test]
9354 fn test_dup_htlc_second_rejected() {
9355         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9356         // simply reject the second HTLC but are still able to claim the first HTLC.
9357         do_test_dup_htlc_second_rejected(false);
9358 }
9359
9360 #[test]
9361 fn test_inconsistent_mpp_params() {
9362         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9363         // such HTLC and allow the second to stay.
9364         let chanmon_cfgs = create_chanmon_cfgs(4);
9365         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9366         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9367         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9368
9369         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9370         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9371         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9372         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9373
9374         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9375                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9376         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9377         assert_eq!(route.paths.len(), 2);
9378         route.paths.sort_by(|path_a, _| {
9379                 // Sort the path so that the path through nodes[1] comes first
9380                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9381                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9382         });
9383
9384         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9385
9386         let cur_height = nodes[0].best_block_info().1;
9387         let payment_id = PaymentId([42; 32]);
9388
9389         let session_privs = {
9390                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9391                 // ultimately have, just not right away.
9392                 let mut dup_route = route.clone();
9393                 dup_route.paths.push(route.paths[1].clone());
9394                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9395                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9396         };
9397         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9398                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9399                 &None, session_privs[0]).unwrap();
9400         check_added_monitors!(nodes[0], 1);
9401
9402         {
9403                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9404                 assert_eq!(events.len(), 1);
9405                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9406         }
9407         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9408
9409         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9410                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9411         check_added_monitors!(nodes[0], 1);
9412
9413         {
9414                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9415                 assert_eq!(events.len(), 1);
9416                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9417
9418                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9419                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9420
9421                 expect_pending_htlcs_forwardable!(nodes[2]);
9422                 check_added_monitors!(nodes[2], 1);
9423
9424                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9425                 assert_eq!(events.len(), 1);
9426                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9427
9428                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9429                 check_added_monitors!(nodes[3], 0);
9430                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9431
9432                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9433                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9434                 // post-payment_secrets) and fail back the new HTLC.
9435         }
9436         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9437         nodes[3].node.process_pending_htlc_forwards();
9438         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9439         nodes[3].node.process_pending_htlc_forwards();
9440
9441         check_added_monitors!(nodes[3], 1);
9442
9443         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9444         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9445         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9446
9447         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 }]);
9448         check_added_monitors!(nodes[2], 1);
9449
9450         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9451         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9452         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9453
9454         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9455
9456         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9457                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9458                 &None, session_privs[2]).unwrap();
9459         check_added_monitors!(nodes[0], 1);
9460
9461         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9462         assert_eq!(events.len(), 1);
9463         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9464
9465         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9466         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9467 }
9468
9469 #[test]
9470 fn test_keysend_payments_to_public_node() {
9471         let chanmon_cfgs = create_chanmon_cfgs(2);
9472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9475
9476         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9477         let network_graph = nodes[0].network_graph.clone();
9478         let payer_pubkey = nodes[0].node.get_our_node_id();
9479         let payee_pubkey = nodes[1].node.get_our_node_id();
9480         let route_params = RouteParameters {
9481                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9482                 final_value_msat: 10000,
9483         };
9484         let scorer = test_utils::TestScorer::new();
9485         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9486         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9487
9488         let test_preimage = PaymentPreimage([42; 32]);
9489         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9490                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9491         check_added_monitors!(nodes[0], 1);
9492         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9493         assert_eq!(events.len(), 1);
9494         let event = events.pop().unwrap();
9495         let path = vec![&nodes[1]];
9496         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9497         claim_payment(&nodes[0], &path, test_preimage);
9498 }
9499
9500 #[test]
9501 fn test_keysend_payments_to_private_node() {
9502         let chanmon_cfgs = create_chanmon_cfgs(2);
9503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9506
9507         let payer_pubkey = nodes[0].node.get_our_node_id();
9508         let payee_pubkey = nodes[1].node.get_our_node_id();
9509
9510         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9511         let route_params = RouteParameters {
9512                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9513                 final_value_msat: 10000,
9514         };
9515         let network_graph = nodes[0].network_graph.clone();
9516         let first_hops = nodes[0].node.list_usable_channels();
9517         let scorer = test_utils::TestScorer::new();
9518         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9519         let route = find_route(
9520                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9521                 nodes[0].logger, &scorer, &(), &random_seed_bytes
9522         ).unwrap();
9523
9524         let test_preimage = PaymentPreimage([42; 32]);
9525         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9526                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9527         check_added_monitors!(nodes[0], 1);
9528         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9529         assert_eq!(events.len(), 1);
9530         let event = events.pop().unwrap();
9531         let path = vec![&nodes[1]];
9532         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9533         claim_payment(&nodes[0], &path, test_preimage);
9534 }
9535
9536 #[test]
9537 fn test_double_partial_claim() {
9538         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9539         // time out, the sender resends only some of the MPP parts, then the user processes the
9540         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9541         // amount.
9542         let chanmon_cfgs = create_chanmon_cfgs(4);
9543         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9544         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9545         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9546
9547         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9548         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9549         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9550         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9551
9552         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9553         assert_eq!(route.paths.len(), 2);
9554         route.paths.sort_by(|path_a, _| {
9555                 // Sort the path so that the path through nodes[1] comes first
9556                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9557                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9558         });
9559
9560         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9561         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9562         // amount of time to respond to.
9563
9564         // Connect some blocks to time out the payment
9565         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9566         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9567
9568         let failed_destinations = vec![
9569                 HTLCDestination::FailedPayment { payment_hash },
9570                 HTLCDestination::FailedPayment { payment_hash },
9571         ];
9572         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9573
9574         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9575
9576         // nodes[1] now retries one of the two paths...
9577         nodes[0].node.send_payment_with_route(&route, payment_hash,
9578                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9579         check_added_monitors!(nodes[0], 2);
9580
9581         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9582         assert_eq!(events.len(), 2);
9583         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9584         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9585
9586         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9587         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9588         nodes[3].node.claim_funds(payment_preimage);
9589         check_added_monitors!(nodes[3], 0);
9590         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9591 }
9592
9593 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9594 #[derive(Clone, Copy, PartialEq)]
9595 enum ExposureEvent {
9596         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9597         AtHTLCForward,
9598         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9599         AtHTLCReception,
9600         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9601         AtUpdateFeeOutbound,
9602 }
9603
9604 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9605         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9606         // policy.
9607         //
9608         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9609         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9610         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9611         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9612         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9613         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9614         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9615         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9616
9617         let chanmon_cfgs = create_chanmon_cfgs(2);
9618         let mut config = test_default_channel_config();
9619         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9620         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9621         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9622         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9623
9624         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9625         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9626         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9627         open_channel.max_accepted_htlcs = 60;
9628         if on_holder_tx {
9629                 open_channel.dust_limit_satoshis = 546;
9630         }
9631         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9632         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9633         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9634
9635         let opt_anchors = false;
9636
9637         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9638
9639         if on_holder_tx {
9640                 let mut node_0_per_peer_lock;
9641                 let mut node_0_peer_state_lock;
9642                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9643                 chan.holder_dust_limit_satoshis = 546;
9644         }
9645
9646         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9647         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()));
9648         check_added_monitors!(nodes[1], 1);
9649         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9650
9651         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()));
9652         check_added_monitors!(nodes[0], 1);
9653         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9654
9655         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9656         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9657         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9658
9659         let dust_buffer_feerate = {
9660                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9661                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9662                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9663                 chan.get_dust_buffer_feerate(None) as u64
9664         };
9665         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;
9666         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9667
9668         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;
9669         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9670
9671         let dust_htlc_on_counterparty_tx: u64 = 25;
9672         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9673
9674         if on_holder_tx {
9675                 if dust_outbound_balance {
9676                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9677                         // Outbound dust balance: 4372 sats
9678                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9679                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9680                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9681                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9682                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9683                         }
9684                 } else {
9685                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9686                         // Inbound dust balance: 4372 sats
9687                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9688                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9689                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9690                         }
9691                 }
9692         } else {
9693                 if dust_outbound_balance {
9694                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9695                         // Outbound dust balance: 5000 sats
9696                         for _ in 0..dust_htlc_on_counterparty_tx {
9697                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9698                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9699                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9700                         }
9701                 } else {
9702                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9703                         // Inbound dust balance: 5000 sats
9704                         for _ in 0..dust_htlc_on_counterparty_tx {
9705                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9706                         }
9707                 }
9708         }
9709
9710         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9711         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9712                 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 });
9713                 let mut config = UserConfig::default();
9714                 // With default dust exposure: 5000 sats
9715                 if on_holder_tx {
9716                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9717                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9718                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9719                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9720                                 ), true, APIError::ChannelUnavailable { ref err },
9721                                 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)));
9722                 } else {
9723                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9724                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9725                                 ), true, APIError::ChannelUnavailable { ref err },
9726                                 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)));
9727                 }
9728         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9729                 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 });
9730                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9731                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9732                 check_added_monitors!(nodes[1], 1);
9733                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9734                 assert_eq!(events.len(), 1);
9735                 let payment_event = SendEvent::from_event(events.remove(0));
9736                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9737                 // With default dust exposure: 5000 sats
9738                 if on_holder_tx {
9739                         // Outbound dust balance: 6399 sats
9740                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9741                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9742                         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);
9743                 } else {
9744                         // Outbound dust balance: 5200 sats
9745                         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);
9746                 }
9747         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9748                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9749                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9750                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9751                 {
9752                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9753                         *feerate_lock = *feerate_lock * 10;
9754                 }
9755                 nodes[0].node.timer_tick_occurred();
9756                 check_added_monitors!(nodes[0], 1);
9757                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9758         }
9759
9760         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9761         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9762         added_monitors.clear();
9763 }
9764
9765 #[test]
9766 fn test_max_dust_htlc_exposure() {
9767         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9768         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9769         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9770         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9771         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9772         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9773         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9774         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9775         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9776         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9777         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9778         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9779 }
9780
9781 #[test]
9782 fn test_non_final_funding_tx() {
9783         let chanmon_cfgs = create_chanmon_cfgs(2);
9784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9786         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9787
9788         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9789         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9790         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9791         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9792         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9793
9794         let best_height = nodes[0].node.best_block.read().unwrap().height();
9795
9796         let chan_id = *nodes[0].network_chan_count.borrow();
9797         let events = nodes[0].node.get_and_clear_pending_events();
9798         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9799         assert_eq!(events.len(), 1);
9800         let mut tx = match events[0] {
9801                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9802                         // Timelock the transaction _beyond_ the best client height + 1.
9803                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9804                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9805                         }]}
9806                 },
9807                 _ => panic!("Unexpected event"),
9808         };
9809         // Transaction should fail as it's evaluated as non-final for propagation.
9810         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9811                 Err(APIError::APIMisuseError { err }) => {
9812                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9813                 },
9814                 _ => panic!()
9815         }
9816
9817         // However, transaction should be accepted if it's in a +1 headroom from best block.
9818         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9819         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9820         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9821 }
9822
9823 #[test]
9824 fn accept_busted_but_better_fee() {
9825         // If a peer sends us a fee update that is too low, but higher than our previous channel
9826         // feerate, we should accept it. In the future we may want to consider closing the channel
9827         // later, but for now we only accept the update.
9828         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9829         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9830         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9831         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9832
9833         create_chan_between_nodes(&nodes[0], &nodes[1]);
9834
9835         // Set nodes[1] to expect 5,000 sat/kW.
9836         {
9837                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9838                 *feerate_lock = 5000;
9839         }
9840
9841         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9842         {
9843                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9844                 *feerate_lock = 1000;
9845         }
9846         nodes[0].node.timer_tick_occurred();
9847         check_added_monitors!(nodes[0], 1);
9848
9849         let events = nodes[0].node.get_and_clear_pending_msg_events();
9850         assert_eq!(events.len(), 1);
9851         match events[0] {
9852                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9853                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9854                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9855                 },
9856                 _ => panic!("Unexpected event"),
9857         };
9858
9859         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9860         // it.
9861         {
9862                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9863                 *feerate_lock = 2000;
9864         }
9865         nodes[0].node.timer_tick_occurred();
9866         check_added_monitors!(nodes[0], 1);
9867
9868         let events = nodes[0].node.get_and_clear_pending_msg_events();
9869         assert_eq!(events.len(), 1);
9870         match events[0] {
9871                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9872                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9873                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9874                 },
9875                 _ => panic!("Unexpected event"),
9876         };
9877
9878         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9879         // channel.
9880         {
9881                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9882                 *feerate_lock = 1000;
9883         }
9884         nodes[0].node.timer_tick_occurred();
9885         check_added_monitors!(nodes[0], 1);
9886
9887         let events = nodes[0].node.get_and_clear_pending_msg_events();
9888         assert_eq!(events.len(), 1);
9889         match events[0] {
9890                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9891                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9892                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9893                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9894                         check_closed_broadcast!(nodes[1], true);
9895                         check_added_monitors!(nodes[1], 1);
9896                 },
9897                 _ => panic!("Unexpected event"),
9898         };
9899 }
9900
9901 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9902         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9906         let min_final_cltv_expiry_delta = 120;
9907         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9908                 min_final_cltv_expiry_delta - 2 };
9909         let recv_value = 100_000;
9910
9911         create_chan_between_nodes(&nodes[0], &nodes[1]);
9912
9913         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9914         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9915                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9916                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9917                 (payment_hash, payment_preimage, payment_secret)
9918         } else {
9919                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9920                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9921         };
9922         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9923         nodes[0].node.send_payment_with_route(&route, payment_hash,
9924                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9925         check_added_monitors!(nodes[0], 1);
9926         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9927         assert_eq!(events.len(), 1);
9928         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9929         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9930         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9931         expect_pending_htlcs_forwardable!(nodes[1]);
9932
9933         if valid_delta {
9934                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9935                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9936
9937                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9938         } else {
9939                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9940
9941                 check_added_monitors!(nodes[1], 1);
9942
9943                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9944                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9945                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9946
9947                 expect_payment_failed!(nodes[0], payment_hash, true);
9948         }
9949 }
9950
9951 #[test]
9952 fn test_payment_with_custom_min_cltv_expiry_delta() {
9953         do_payment_with_custom_min_final_cltv_expiry(false, false);
9954         do_payment_with_custom_min_final_cltv_expiry(false, true);
9955         do_payment_with_custom_min_final_cltv_expiry(true, false);
9956         do_payment_with_custom_min_final_cltv_expiry(true, true);
9957 }