Move inbound channel methods into `InboundV1Channel`'s impl
[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, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel};
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::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, 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 = 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 -= 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                 if send_from_initiator {
183                         let chan = get_inbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
184                         chan.context.holder_selected_channel_reserve_satoshis = 0;
185                         chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
186                 } else {
187                         let chan = get_outbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
188                         chan.context.holder_selected_channel_reserve_satoshis = 0;
189                         chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
190                 }
191         }
192
193         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
194         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
195         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
196
197         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
198         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
199         if send_from_initiator {
200                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
201                         // Note that for outbound channels we have to consider the commitment tx fee and the
202                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
203                         // well as an additional HTLC.
204                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
205         } else {
206                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
207         }
208 }
209
210 #[test]
211 fn test_counterparty_no_reserve() {
212         do_test_counterparty_no_reserve(true);
213         do_test_counterparty_no_reserve(false);
214 }
215
216 #[test]
217 fn test_async_inbound_update_fee() {
218         let chanmon_cfgs = create_chanmon_cfgs(2);
219         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
220         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
221         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
222         create_announced_chan_between_nodes(&nodes, 0, 1);
223
224         // balancing
225         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
226
227         // A                                        B
228         // update_fee                            ->
229         // send (1) commitment_signed            -.
230         //                                       <- update_add_htlc/commitment_signed
231         // send (2) RAA (awaiting remote revoke) -.
232         // (1) commitment_signed is delivered    ->
233         //                                       .- send (3) RAA (awaiting remote revoke)
234         // (2) RAA is delivered                  ->
235         //                                       .- send (4) commitment_signed
236         //                                       <- (3) RAA is delivered
237         // send (5) commitment_signed            -.
238         //                                       <- (4) commitment_signed is delivered
239         // send (6) RAA                          -.
240         // (5) commitment_signed is delivered    ->
241         //                                       <- RAA
242         // (6) RAA is delivered                  ->
243
244         // First nodes[0] generates an update_fee
245         {
246                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
247                 *feerate_lock += 20;
248         }
249         nodes[0].node.timer_tick_occurred();
250         check_added_monitors!(nodes[0], 1);
251
252         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253         assert_eq!(events_0.len(), 1);
254         let (update_msg, commitment_signed) = match events_0[0] { // (1)
255                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
256                         (update_fee.as_ref(), commitment_signed)
257                 },
258                 _ => panic!("Unexpected event"),
259         };
260
261         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262
263         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
265         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
266                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
267         check_added_monitors!(nodes[1], 1);
268
269         let payment_event = {
270                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271                 assert_eq!(events_1.len(), 1);
272                 SendEvent::from_event(events_1.remove(0))
273         };
274         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275         assert_eq!(payment_event.msgs.len(), 1);
276
277         // ...now when the messages get delivered everyone should be happy
278         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[0], 1);
283
284         // deliver(1), generate (3):
285         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
286         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
287         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
288         check_added_monitors!(nodes[1], 1);
289
290         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
291         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
292         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
293         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
294         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
295         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
296         assert!(bs_update.update_fee.is_none()); // (4)
297         check_added_monitors!(nodes[1], 1);
298
299         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
300         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
301         assert!(as_update.update_add_htlcs.is_empty()); // (5)
302         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
303         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
304         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
305         assert!(as_update.update_fee.is_none()); // (5)
306         check_added_monitors!(nodes[0], 1);
307
308         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
309         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
310         // only (6) so get_event_msg's assert(len == 1) passes
311         check_added_monitors!(nodes[0], 1);
312
313         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
314         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
315         check_added_monitors!(nodes[1], 1);
316
317         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
318         check_added_monitors!(nodes[0], 1);
319
320         let events_2 = nodes[0].node.get_and_clear_pending_events();
321         assert_eq!(events_2.len(), 1);
322         match events_2[0] {
323                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
324                 _ => panic!("Unexpected event"),
325         }
326
327         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
328         check_added_monitors!(nodes[1], 1);
329 }
330
331 #[test]
332 fn test_update_fee_unordered_raa() {
333         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
334         // crash in an earlier version of the update_fee patch)
335         let chanmon_cfgs = create_chanmon_cfgs(2);
336         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
337         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
338         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
339         create_announced_chan_between_nodes(&nodes, 0, 1);
340
341         // balancing
342         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
343
344         // First nodes[0] generates an update_fee
345         {
346                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
347                 *feerate_lock += 20;
348         }
349         nodes[0].node.timer_tick_occurred();
350         check_added_monitors!(nodes[0], 1);
351
352         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
353         assert_eq!(events_0.len(), 1);
354         let update_msg = match events_0[0] { // (1)
355                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
356                         update_fee.as_ref()
357                 },
358                 _ => panic!("Unexpected event"),
359         };
360
361         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
362
363         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
364         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
365         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
366                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
367         check_added_monitors!(nodes[1], 1);
368
369         let payment_event = {
370                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
371                 assert_eq!(events_1.len(), 1);
372                 SendEvent::from_event(events_1.remove(0))
373         };
374         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
375         assert_eq!(payment_event.msgs.len(), 1);
376
377         // ...now when the messages get delivered everyone should be happy
378         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
379         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
380         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
381         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
382         check_added_monitors!(nodes[0], 1);
383
384         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
385         check_added_monitors!(nodes[1], 1);
386
387         // We can't continue, sadly, because our (1) now has a bogus signature
388 }
389
390 #[test]
391 fn test_multi_flight_update_fee() {
392         let chanmon_cfgs = create_chanmon_cfgs(2);
393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
395         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
396         create_announced_chan_between_nodes(&nodes, 0, 1);
397
398         // A                                        B
399         // update_fee/commitment_signed          ->
400         //                                       .- send (1) RAA and (2) commitment_signed
401         // update_fee (never committed)          ->
402         // (3) update_fee                        ->
403         // We have to manually generate the above update_fee, it is allowed by the protocol but we
404         // don't track which updates correspond to which revoke_and_ack responses so we're in
405         // AwaitingRAA mode and will not generate the update_fee yet.
406         //                                       <- (1) RAA delivered
407         // (3) is generated and send (4) CS      -.
408         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
409         // know the per_commitment_point to use for it.
410         //                                       <- (2) commitment_signed delivered
411         // revoke_and_ack                        ->
412         //                                          B should send no response here
413         // (4) commitment_signed delivered       ->
414         //                                       <- RAA/commitment_signed delivered
415         // revoke_and_ack                        ->
416
417         // First nodes[0] generates an update_fee
418         let initial_feerate;
419         {
420                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
421                 initial_feerate = *feerate_lock;
422                 *feerate_lock = initial_feerate + 20;
423         }
424         nodes[0].node.timer_tick_occurred();
425         check_added_monitors!(nodes[0], 1);
426
427         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
428         assert_eq!(events_0.len(), 1);
429         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
430                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
431                         (update_fee.as_ref().unwrap(), commitment_signed)
432                 },
433                 _ => panic!("Unexpected event"),
434         };
435
436         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
437         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
438         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
439         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
440         check_added_monitors!(nodes[1], 1);
441
442         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
443         // transaction:
444         {
445                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
446                 *feerate_lock = initial_feerate + 40;
447         }
448         nodes[0].node.timer_tick_occurred();
449         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
450         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
451
452         // Create the (3) update_fee message that nodes[0] will generate before it does...
453         let mut update_msg_2 = msgs::UpdateFee {
454                 channel_id: update_msg_1.channel_id.clone(),
455                 feerate_per_kw: (initial_feerate + 30) as u32,
456         };
457
458         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
459
460         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
461         // Deliver (3)
462         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
463
464         // Deliver (1), generating (3) and (4)
465         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
466         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
467         check_added_monitors!(nodes[0], 1);
468         assert!(as_second_update.update_add_htlcs.is_empty());
469         assert!(as_second_update.update_fulfill_htlcs.is_empty());
470         assert!(as_second_update.update_fail_htlcs.is_empty());
471         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
472         // Check that the update_fee newly generated matches what we delivered:
473         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
474         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
475
476         // Deliver (2) commitment_signed
477         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
478         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
479         check_added_monitors!(nodes[0], 1);
480         // No commitment_signed so get_event_msg's assert(len == 1) passes
481
482         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
483         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
484         check_added_monitors!(nodes[1], 1);
485
486         // Delever (4)
487         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
488         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
489         check_added_monitors!(nodes[1], 1);
490
491         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
492         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
493         check_added_monitors!(nodes[0], 1);
494
495         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
496         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
497         // No commitment_signed so get_event_msg's assert(len == 1) passes
498         check_added_monitors!(nodes[0], 1);
499
500         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
501         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
502         check_added_monitors!(nodes[1], 1);
503 }
504
505 fn do_test_sanity_on_in_flight_opens(steps: u8) {
506         // Previously, we had issues deserializing channels when we hadn't connected the first block
507         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
508         // serialization round-trips and simply do steps towards opening a channel and then drop the
509         // Node objects.
510
511         let chanmon_cfgs = create_chanmon_cfgs(2);
512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
514         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
515
516         if steps & 0b1000_0000 != 0{
517                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
518                 connect_block(&nodes[0], &block);
519                 connect_block(&nodes[1], &block);
520         }
521
522         if steps & 0x0f == 0 { return; }
523         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
524         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
525
526         if steps & 0x0f == 1 { return; }
527         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
528         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
529
530         if steps & 0x0f == 2 { return; }
531         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
532
533         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
534
535         if steps & 0x0f == 3 { return; }
536         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
537         check_added_monitors!(nodes[0], 0);
538         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
539
540         if steps & 0x0f == 4 { return; }
541         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
542         {
543                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
544                 assert_eq!(added_monitors.len(), 1);
545                 assert_eq!(added_monitors[0].0, funding_output);
546                 added_monitors.clear();
547         }
548         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
549
550         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
551
552         if steps & 0x0f == 5 { return; }
553         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
554         {
555                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
556                 assert_eq!(added_monitors.len(), 1);
557                 assert_eq!(added_monitors[0].0, funding_output);
558                 added_monitors.clear();
559         }
560
561         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
562         let events_4 = nodes[0].node.get_and_clear_pending_events();
563         assert_eq!(events_4.len(), 0);
564
565         if steps & 0x0f == 6 { return; }
566         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
567
568         if steps & 0x0f == 7 { return; }
569         confirm_transaction_at(&nodes[0], &tx, 2);
570         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
571         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
572         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
573 }
574
575 #[test]
576 fn test_sanity_on_in_flight_opens() {
577         do_test_sanity_on_in_flight_opens(0);
578         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(1);
580         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(2);
582         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(3);
584         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(4);
586         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(5);
588         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(6);
590         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
591         do_test_sanity_on_in_flight_opens(7);
592         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
593         do_test_sanity_on_in_flight_opens(8);
594         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
595 }
596
597 #[test]
598 fn test_update_fee_vanilla() {
599         let chanmon_cfgs = create_chanmon_cfgs(2);
600         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
602         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
603         create_announced_chan_between_nodes(&nodes, 0, 1);
604
605         {
606                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
607                 *feerate_lock += 25;
608         }
609         nodes[0].node.timer_tick_occurred();
610         check_added_monitors!(nodes[0], 1);
611
612         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
613         assert_eq!(events_0.len(), 1);
614         let (update_msg, commitment_signed) = match events_0[0] {
615                         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 } } => {
616                         (update_fee.as_ref(), commitment_signed)
617                 },
618                 _ => panic!("Unexpected event"),
619         };
620         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
621
622         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
623         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
624         check_added_monitors!(nodes[1], 1);
625
626         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
627         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
628         check_added_monitors!(nodes[0], 1);
629
630         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
631         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
632         // No commitment_signed so get_event_msg's assert(len == 1) passes
633         check_added_monitors!(nodes[0], 1);
634
635         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
636         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
637         check_added_monitors!(nodes[1], 1);
638 }
639
640 #[test]
641 fn test_update_fee_that_funder_cannot_afford() {
642         let chanmon_cfgs = create_chanmon_cfgs(2);
643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
645         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
646         let channel_value = 5000;
647         let push_sats = 700;
648         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
649         let channel_id = chan.2;
650         let secp_ctx = Secp256k1::new();
651         let default_config = UserConfig::default();
652         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
653
654         let opt_anchors = false;
655
656         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
657         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
658         // calculate two different feerates here - the expected local limit as well as the expected
659         // remote limit.
660         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;
661         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
662         {
663                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
664                 *feerate_lock = feerate;
665         }
666         nodes[0].node.timer_tick_occurred();
667         check_added_monitors!(nodes[0], 1);
668         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
669
670         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
671
672         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
673
674         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
675         {
676                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
677
678                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
679                 assert_eq!(commitment_tx.output.len(), 2);
680                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
681                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
682                 actual_fee = channel_value - actual_fee;
683                 assert_eq!(total_fee, actual_fee);
684         }
685
686         {
687                 // Increment the feerate by a small constant, accounting for rounding errors
688                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
689                 *feerate_lock += 4;
690         }
691         nodes[0].node.timer_tick_occurred();
692         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
693         check_added_monitors!(nodes[0], 0);
694
695         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
696
697         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
698         // needed to sign the new commitment tx and (2) sign the new commitment tx.
699         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
700                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
701                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
702                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
703                 let chan_signer = local_chan.get_signer();
704                 let pubkeys = chan_signer.pubkeys();
705                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
706                  pubkeys.funding_pubkey)
707         };
708         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
709                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
710                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
711                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
712                 let chan_signer = remote_chan.get_signer();
713                 let pubkeys = chan_signer.pubkeys();
714                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
715                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
716                  pubkeys.funding_pubkey)
717         };
718
719         // Assemble the set of keys we can use for signatures for our commitment_signed message.
720         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
721                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
722
723         let res = {
724                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
725                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
726                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
727                 let local_chan_signer = local_chan.get_signer();
728                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
729                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
730                         INITIAL_COMMITMENT_NUMBER - 1,
731                         push_sats,
732                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
733                         opt_anchors, local_funding, remote_funding,
734                         commit_tx_keys.clone(),
735                         non_buffer_feerate + 4,
736                         &mut htlcs,
737                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
738                 );
739                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
740         };
741
742         let commit_signed_msg = msgs::CommitmentSigned {
743                 channel_id: chan.2,
744                 signature: res.0,
745                 htlc_signatures: res.1,
746                 #[cfg(taproot)]
747                 partial_signature_with_nonce: None,
748         };
749
750         let update_fee = msgs::UpdateFee {
751                 channel_id: chan.2,
752                 feerate_per_kw: non_buffer_feerate + 4,
753         };
754
755         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
756
757         //While producing the commitment_signed response after handling a received update_fee request the
758         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
759         //Should produce and error.
760         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
761         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
762         check_added_monitors!(nodes[1], 1);
763         check_closed_broadcast!(nodes[1], true);
764         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
765 }
766
767 #[test]
768 fn test_update_fee_with_fundee_update_add_htlc() {
769         let chanmon_cfgs = create_chanmon_cfgs(2);
770         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
772         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
773         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
774
775         // balancing
776         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
777
778         {
779                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
780                 *feerate_lock += 20;
781         }
782         nodes[0].node.timer_tick_occurred();
783         check_added_monitors!(nodes[0], 1);
784
785         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
786         assert_eq!(events_0.len(), 1);
787         let (update_msg, commitment_signed) = match events_0[0] {
788                         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 } } => {
789                         (update_fee.as_ref(), commitment_signed)
790                 },
791                 _ => panic!("Unexpected event"),
792         };
793         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
794         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
795         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
796         check_added_monitors!(nodes[1], 1);
797
798         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
799
800         // nothing happens since node[1] is in AwaitingRemoteRevoke
801         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
802                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
803         {
804                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
805                 assert_eq!(added_monitors.len(), 0);
806                 added_monitors.clear();
807         }
808         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
809         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
810         // node[1] has nothing to do
811
812         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
813         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
814         check_added_monitors!(nodes[0], 1);
815
816         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
817         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
818         // No commitment_signed so get_event_msg's assert(len == 1) passes
819         check_added_monitors!(nodes[0], 1);
820         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
821         check_added_monitors!(nodes[1], 1);
822         // AwaitingRemoteRevoke ends here
823
824         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
825         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
826         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
827         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
828         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
829         assert_eq!(commitment_update.update_fee.is_none(), true);
830
831         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
832         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
833         check_added_monitors!(nodes[0], 1);
834         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
835
836         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
837         check_added_monitors!(nodes[1], 1);
838         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
839
840         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
841         check_added_monitors!(nodes[1], 1);
842         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
843         // No commitment_signed so get_event_msg's assert(len == 1) passes
844
845         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
846         check_added_monitors!(nodes[0], 1);
847         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
848
849         expect_pending_htlcs_forwardable!(nodes[0]);
850
851         let events = nodes[0].node.get_and_clear_pending_events();
852         assert_eq!(events.len(), 1);
853         match events[0] {
854                 Event::PaymentClaimable { .. } => { },
855                 _ => panic!("Unexpected event"),
856         };
857
858         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
859
860         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
861         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
862         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
863         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
864         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
865 }
866
867 #[test]
868 fn test_update_fee() {
869         let chanmon_cfgs = create_chanmon_cfgs(2);
870         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
871         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
872         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
873         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
874         let channel_id = chan.2;
875
876         // A                                        B
877         // (1) update_fee/commitment_signed      ->
878         //                                       <- (2) revoke_and_ack
879         //                                       .- send (3) commitment_signed
880         // (4) update_fee/commitment_signed      ->
881         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
882         //                                       <- (3) commitment_signed delivered
883         // send (6) revoke_and_ack               -.
884         //                                       <- (5) deliver revoke_and_ack
885         // (6) deliver revoke_and_ack            ->
886         //                                       .- send (7) commitment_signed in response to (4)
887         //                                       <- (7) deliver commitment_signed
888         // revoke_and_ack                        ->
889
890         // Create and deliver (1)...
891         let feerate;
892         {
893                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
894                 feerate = *feerate_lock;
895                 *feerate_lock = feerate + 20;
896         }
897         nodes[0].node.timer_tick_occurred();
898         check_added_monitors!(nodes[0], 1);
899
900         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
901         assert_eq!(events_0.len(), 1);
902         let (update_msg, commitment_signed) = match events_0[0] {
903                         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 } } => {
904                         (update_fee.as_ref(), commitment_signed)
905                 },
906                 _ => panic!("Unexpected event"),
907         };
908         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
909
910         // Generate (2) and (3):
911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
912         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
913         check_added_monitors!(nodes[1], 1);
914
915         // Deliver (2):
916         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
917         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
918         check_added_monitors!(nodes[0], 1);
919
920         // Create and deliver (4)...
921         {
922                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
923                 *feerate_lock = feerate + 30;
924         }
925         nodes[0].node.timer_tick_occurred();
926         check_added_monitors!(nodes[0], 1);
927         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
928         assert_eq!(events_0.len(), 1);
929         let (update_msg, commitment_signed) = match events_0[0] {
930                         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 } } => {
931                         (update_fee.as_ref(), commitment_signed)
932                 },
933                 _ => panic!("Unexpected event"),
934         };
935
936         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
937         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
938         check_added_monitors!(nodes[1], 1);
939         // ... creating (5)
940         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
941         // No commitment_signed so get_event_msg's assert(len == 1) passes
942
943         // Handle (3), creating (6):
944         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
945         check_added_monitors!(nodes[0], 1);
946         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
947         // No commitment_signed so get_event_msg's assert(len == 1) passes
948
949         // Deliver (5):
950         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
951         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
952         check_added_monitors!(nodes[0], 1);
953
954         // Deliver (6), creating (7):
955         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
956         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
957         assert!(commitment_update.update_add_htlcs.is_empty());
958         assert!(commitment_update.update_fulfill_htlcs.is_empty());
959         assert!(commitment_update.update_fail_htlcs.is_empty());
960         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
961         assert!(commitment_update.update_fee.is_none());
962         check_added_monitors!(nodes[1], 1);
963
964         // Deliver (7)
965         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
966         check_added_monitors!(nodes[0], 1);
967         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
968         // No commitment_signed so get_event_msg's assert(len == 1) passes
969
970         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
971         check_added_monitors!(nodes[1], 1);
972         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
973
974         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
975         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
976         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
977         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
978         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
979 }
980
981 #[test]
982 fn fake_network_test() {
983         // Simple test which builds a network of ChannelManagers, connects them to each other, and
984         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
985         let chanmon_cfgs = create_chanmon_cfgs(4);
986         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
987         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
988         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
989
990         // Create some initial channels
991         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
992         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
993         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
994
995         // Rebalance the network a bit by relaying one payment through all the channels...
996         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
997         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
998         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
999         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1000
1001         // Send some more payments
1002         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1003         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1004         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1005
1006         // Test failure packets
1007         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1008         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1009
1010         // Add a new channel that skips 3
1011         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1012
1013         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1014         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1015         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1016         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1017         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1018         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1020
1021         // Do some rebalance loop payments, simultaneously
1022         let mut hops = Vec::with_capacity(3);
1023         hops.push(RouteHop {
1024                 pubkey: nodes[2].node.get_our_node_id(),
1025                 node_features: NodeFeatures::empty(),
1026                 short_channel_id: chan_2.0.contents.short_channel_id,
1027                 channel_features: ChannelFeatures::empty(),
1028                 fee_msat: 0,
1029                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1030         });
1031         hops.push(RouteHop {
1032                 pubkey: nodes[3].node.get_our_node_id(),
1033                 node_features: NodeFeatures::empty(),
1034                 short_channel_id: chan_3.0.contents.short_channel_id,
1035                 channel_features: ChannelFeatures::empty(),
1036                 fee_msat: 0,
1037                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1038         });
1039         hops.push(RouteHop {
1040                 pubkey: nodes[1].node.get_our_node_id(),
1041                 node_features: nodes[1].node.node_features(),
1042                 short_channel_id: chan_4.0.contents.short_channel_id,
1043                 channel_features: nodes[1].node.channel_features(),
1044                 fee_msat: 1000000,
1045                 cltv_expiry_delta: TEST_FINAL_CLTV,
1046         });
1047         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;
1048         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;
1049         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;
1050
1051         let mut hops = Vec::with_capacity(3);
1052         hops.push(RouteHop {
1053                 pubkey: nodes[3].node.get_our_node_id(),
1054                 node_features: NodeFeatures::empty(),
1055                 short_channel_id: chan_4.0.contents.short_channel_id,
1056                 channel_features: ChannelFeatures::empty(),
1057                 fee_msat: 0,
1058                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1059         });
1060         hops.push(RouteHop {
1061                 pubkey: nodes[2].node.get_our_node_id(),
1062                 node_features: NodeFeatures::empty(),
1063                 short_channel_id: chan_3.0.contents.short_channel_id,
1064                 channel_features: ChannelFeatures::empty(),
1065                 fee_msat: 0,
1066                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1067         });
1068         hops.push(RouteHop {
1069                 pubkey: nodes[1].node.get_our_node_id(),
1070                 node_features: nodes[1].node.node_features(),
1071                 short_channel_id: chan_2.0.contents.short_channel_id,
1072                 channel_features: nodes[1].node.channel_features(),
1073                 fee_msat: 1000000,
1074                 cltv_expiry_delta: TEST_FINAL_CLTV,
1075         });
1076         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;
1077         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;
1078         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;
1079
1080         // Claim the rebalances...
1081         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1082         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1083
1084         // Close down the channels...
1085         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1086         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1091         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1092         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1093         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1095         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1097 }
1098
1099 #[test]
1100 fn holding_cell_htlc_counting() {
1101         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1102         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1103         // commitment dance rounds.
1104         let chanmon_cfgs = create_chanmon_cfgs(3);
1105         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1106         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1107         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1108         create_announced_chan_between_nodes(&nodes, 0, 1);
1109         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1110
1111         // Fetch a route in advance as we will be unable to once we're unable to send.
1112         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1113
1114         let mut payments = Vec::new();
1115         for _ in 0..50 {
1116                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1117                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1118                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1119                 payments.push((payment_preimage, payment_hash));
1120         }
1121         check_added_monitors!(nodes[1], 1);
1122
1123         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1124         assert_eq!(events.len(), 1);
1125         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1126         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1127
1128         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1129         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1130         // another HTLC.
1131         {
1132                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1133                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1134                         ), true, APIError::ChannelUnavailable { .. }, {});
1135                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1136         }
1137
1138         // This should also be true if we try to forward a payment.
1139         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1140         {
1141                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1142                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1143                 check_added_monitors!(nodes[0], 1);
1144         }
1145
1146         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1147         assert_eq!(events.len(), 1);
1148         let payment_event = SendEvent::from_event(events.pop().unwrap());
1149         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1150
1151         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1152         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1153         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1154         // fails), the second will process the resulting failure and fail the HTLC backward.
1155         expect_pending_htlcs_forwardable!(nodes[1]);
1156         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 }]);
1157         check_added_monitors!(nodes[1], 1);
1158
1159         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1160         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1161         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1162
1163         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1164
1165         // Now forward all the pending HTLCs and claim them back
1166         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1167         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1168         check_added_monitors!(nodes[2], 1);
1169
1170         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1171         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1172         check_added_monitors!(nodes[1], 1);
1173         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1174
1175         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1176         check_added_monitors!(nodes[1], 1);
1177         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1178
1179         for ref update in as_updates.update_add_htlcs.iter() {
1180                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1181         }
1182         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1183         check_added_monitors!(nodes[2], 1);
1184         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1185         check_added_monitors!(nodes[2], 1);
1186         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1187
1188         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1189         check_added_monitors!(nodes[1], 1);
1190         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1191         check_added_monitors!(nodes[1], 1);
1192         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1193
1194         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1195         check_added_monitors!(nodes[2], 1);
1196
1197         expect_pending_htlcs_forwardable!(nodes[2]);
1198
1199         let events = nodes[2].node.get_and_clear_pending_events();
1200         assert_eq!(events.len(), payments.len());
1201         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1202                 match event {
1203                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1204                                 assert_eq!(*payment_hash, *hash);
1205                         },
1206                         _ => panic!("Unexpected event"),
1207                 };
1208         }
1209
1210         for (preimage, _) in payments.drain(..) {
1211                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1212         }
1213
1214         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1215 }
1216
1217 #[test]
1218 fn duplicate_htlc_test() {
1219         // Test that we accept duplicate payment_hash HTLCs across the network and that
1220         // claiming/failing them are all separate and don't affect each other
1221         let chanmon_cfgs = create_chanmon_cfgs(6);
1222         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1223         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1224         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1225
1226         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1227         create_announced_chan_between_nodes(&nodes, 0, 3);
1228         create_announced_chan_between_nodes(&nodes, 1, 3);
1229         create_announced_chan_between_nodes(&nodes, 2, 3);
1230         create_announced_chan_between_nodes(&nodes, 3, 4);
1231         create_announced_chan_between_nodes(&nodes, 3, 5);
1232
1233         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1234
1235         *nodes[0].network_payment_count.borrow_mut() -= 1;
1236         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1237
1238         *nodes[0].network_payment_count.borrow_mut() -= 1;
1239         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1240
1241         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1242         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1243         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1244 }
1245
1246 #[test]
1247 fn test_duplicate_htlc_different_direction_onchain() {
1248         // Test that ChannelMonitor doesn't generate 2 preimage txn
1249         // when we have 2 HTLCs with same preimage that go across a node
1250         // in opposite directions, even with the same payment secret.
1251         let chanmon_cfgs = create_chanmon_cfgs(2);
1252         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1253         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1254         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1255
1256         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1257
1258         // balancing
1259         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1260
1261         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1262
1263         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1264         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1265         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1266
1267         // Provide preimage to node 0 by claiming payment
1268         nodes[0].node.claim_funds(payment_preimage);
1269         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1270         check_added_monitors!(nodes[0], 1);
1271
1272         // Broadcast node 1 commitment txn
1273         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1274
1275         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1276         let mut has_both_htlcs = 0; // check htlcs match ones committed
1277         for outp in remote_txn[0].output.iter() {
1278                 if outp.value == 800_000 / 1000 {
1279                         has_both_htlcs += 1;
1280                 } else if outp.value == 900_000 / 1000 {
1281                         has_both_htlcs += 1;
1282                 }
1283         }
1284         assert_eq!(has_both_htlcs, 2);
1285
1286         mine_transaction(&nodes[0], &remote_txn[0]);
1287         check_added_monitors!(nodes[0], 1);
1288         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1289         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1290
1291         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1292         assert_eq!(claim_txn.len(), 3);
1293
1294         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1295         check_spends!(claim_txn[1], remote_txn[0]);
1296         check_spends!(claim_txn[2], remote_txn[0]);
1297         let preimage_tx = &claim_txn[0];
1298         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1299                 (&claim_txn[1], &claim_txn[2])
1300         } else {
1301                 (&claim_txn[2], &claim_txn[1])
1302         };
1303
1304         assert_eq!(preimage_tx.input.len(), 1);
1305         assert_eq!(preimage_bump_tx.input.len(), 1);
1306
1307         assert_eq!(preimage_tx.input.len(), 1);
1308         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1309         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1310
1311         assert_eq!(timeout_tx.input.len(), 1);
1312         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1313         check_spends!(timeout_tx, remote_txn[0]);
1314         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1315
1316         let events = nodes[0].node.get_and_clear_pending_msg_events();
1317         assert_eq!(events.len(), 3);
1318         for e in events {
1319                 match e {
1320                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1321                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1322                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1323                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1324                         },
1325                         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, .. } } => {
1326                                 assert!(update_add_htlcs.is_empty());
1327                                 assert!(update_fail_htlcs.is_empty());
1328                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1329                                 assert!(update_fail_malformed_htlcs.is_empty());
1330                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1331                         },
1332                         _ => panic!("Unexpected event"),
1333                 }
1334         }
1335 }
1336
1337 #[test]
1338 fn test_basic_channel_reserve() {
1339         let chanmon_cfgs = create_chanmon_cfgs(2);
1340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1342         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1343         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1344
1345         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1346         let channel_reserve = chan_stat.channel_reserve_msat;
1347
1348         // The 2* and +1 are for the fee spike reserve.
1349         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));
1350         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1351         let (mut route, our_payment_hash, _, our_payment_secret) =
1352                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1353         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1354         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1355                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1356         match err {
1357                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1358                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1359                         else { panic!("Unexpected error variant"); }
1360                 },
1361                 _ => panic!("Unexpected error variant"),
1362         }
1363         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1364
1365         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1366 }
1367
1368 #[test]
1369 fn test_fee_spike_violation_fails_htlc() {
1370         let chanmon_cfgs = create_chanmon_cfgs(2);
1371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1374         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1375
1376         let (mut route, payment_hash, _, payment_secret) =
1377                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1378         route.paths[0].hops[0].fee_msat += 1;
1379         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1380         let secp_ctx = Secp256k1::new();
1381         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1382
1383         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1384
1385         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1386         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1387                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1388         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1389         let msg = msgs::UpdateAddHTLC {
1390                 channel_id: chan.2,
1391                 htlc_id: 0,
1392                 amount_msat: htlc_msat,
1393                 payment_hash: payment_hash,
1394                 cltv_expiry: htlc_cltv,
1395                 onion_routing_packet: onion_packet,
1396         };
1397
1398         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1399
1400         // Now manually create the commitment_signed message corresponding to the update_add
1401         // nodes[0] just sent. In the code for construction of this message, "local" refers
1402         // to the sender of the message, and "remote" refers to the receiver.
1403
1404         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1405
1406         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1407
1408         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1409         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1410         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1411                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1412                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1413                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1414                 let chan_signer = local_chan.get_signer();
1415                 // Make the signer believe we validated another commitment, so we can release the secret
1416                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1417
1418                 let pubkeys = chan_signer.pubkeys();
1419                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1420                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1421                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1422                  chan_signer.pubkeys().funding_pubkey)
1423         };
1424         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1425                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1426                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1427                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1428                 let chan_signer = remote_chan.get_signer();
1429                 let pubkeys = chan_signer.pubkeys();
1430                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1431                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1432                  chan_signer.pubkeys().funding_pubkey)
1433         };
1434
1435         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1436         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1437                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1438
1439         // Build the remote commitment transaction so we can sign it, and then later use the
1440         // signature for the commitment_signed message.
1441         let local_chan_balance = 1313;
1442
1443         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1444                 offered: false,
1445                 amount_msat: 3460001,
1446                 cltv_expiry: htlc_cltv,
1447                 payment_hash,
1448                 transaction_output_index: Some(1),
1449         };
1450
1451         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1452
1453         let res = {
1454                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1455                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1456                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1457                 let local_chan_signer = local_chan.get_signer();
1458                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1459                         commitment_number,
1460                         95000,
1461                         local_chan_balance,
1462                         local_chan.context.opt_anchors(), local_funding, remote_funding,
1463                         commit_tx_keys.clone(),
1464                         feerate_per_kw,
1465                         &mut vec![(accepted_htlc_info, ())],
1466                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1467                 );
1468                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1469         };
1470
1471         let commit_signed_msg = msgs::CommitmentSigned {
1472                 channel_id: chan.2,
1473                 signature: res.0,
1474                 htlc_signatures: res.1,
1475                 #[cfg(taproot)]
1476                 partial_signature_with_nonce: None,
1477         };
1478
1479         // Send the commitment_signed message to the nodes[1].
1480         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1481         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1482
1483         // Send the RAA to nodes[1].
1484         let raa_msg = msgs::RevokeAndACK {
1485                 channel_id: chan.2,
1486                 per_commitment_secret: local_secret,
1487                 next_per_commitment_point: next_local_point,
1488                 #[cfg(taproot)]
1489                 next_local_nonce: None,
1490         };
1491         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1492
1493         let events = nodes[1].node.get_and_clear_pending_msg_events();
1494         assert_eq!(events.len(), 1);
1495         // Make sure the HTLC failed in the way we expect.
1496         match events[0] {
1497                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1498                         assert_eq!(update_fail_htlcs.len(), 1);
1499                         update_fail_htlcs[0].clone()
1500                 },
1501                 _ => panic!("Unexpected event"),
1502         };
1503         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1504                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1505
1506         check_added_monitors!(nodes[1], 2);
1507 }
1508
1509 #[test]
1510 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1511         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1512         // Set the fee rate for the channel very high, to the point where the fundee
1513         // sending any above-dust amount would result in a channel reserve violation.
1514         // In this test we check that we would be prevented from sending an HTLC in
1515         // this situation.
1516         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1519         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1520         let default_config = UserConfig::default();
1521         let opt_anchors = false;
1522
1523         let mut push_amt = 100_000_000;
1524         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1525
1526         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1527
1528         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1529
1530         // Fetch a route in advance as we will be unable to once we're unable to send.
1531         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1532         // Sending exactly enough to hit the reserve amount should be accepted
1533         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1534                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1535         }
1536
1537         // However one more HTLC should be significantly over the reserve amount and fail.
1538         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1539                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1540                 ), true, APIError::ChannelUnavailable { .. }, {});
1541         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1542 }
1543
1544 #[test]
1545 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1546         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1547         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1548         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1549         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1550         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1551         let default_config = UserConfig::default();
1552         let opt_anchors = false;
1553
1554         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1555         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1556         // transaction fee with 0 HTLCs (183 sats)).
1557         let mut push_amt = 100_000_000;
1558         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1559         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1560         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1561
1562         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1563         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1564                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1565         }
1566
1567         let (mut route, payment_hash, _, payment_secret) =
1568                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1569         route.paths[0].hops[0].fee_msat = 700_000;
1570         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1571         let secp_ctx = Secp256k1::new();
1572         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1573         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1574         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1575         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1576                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1577         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1578         let msg = msgs::UpdateAddHTLC {
1579                 channel_id: chan.2,
1580                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1581                 amount_msat: htlc_msat,
1582                 payment_hash: payment_hash,
1583                 cltv_expiry: htlc_cltv,
1584                 onion_routing_packet: onion_packet,
1585         };
1586
1587         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1588         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1589         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);
1590         assert_eq!(nodes[0].node.list_channels().len(), 0);
1591         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1592         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1593         check_added_monitors!(nodes[0], 1);
1594         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() });
1595 }
1596
1597 #[test]
1598 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1599         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1600         // calculating our commitment transaction fee (this was previously broken).
1601         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1602         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1603
1604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1606         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1607         let default_config = UserConfig::default();
1608         let opt_anchors = false;
1609
1610         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1611         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1612         // transaction fee with 0 HTLCs (183 sats)).
1613         let mut push_amt = 100_000_000;
1614         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1615         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1616         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1617
1618         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1619                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1620         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1621         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1622         // commitment transaction fee.
1623         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1624
1625         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1626         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1627                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1628         }
1629
1630         // One more than the dust amt should fail, however.
1631         let (mut route, our_payment_hash, _, our_payment_secret) =
1632                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1633         route.paths[0].hops[0].fee_msat += 1;
1634         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1635                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1636                 ), true, APIError::ChannelUnavailable { .. }, {});
1637 }
1638
1639 #[test]
1640 fn test_chan_init_feerate_unaffordability() {
1641         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1642         // channel reserve and feerate requirements.
1643         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1644         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1647         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1648         let default_config = UserConfig::default();
1649         let opt_anchors = false;
1650
1651         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1652         // HTLC.
1653         let mut push_amt = 100_000_000;
1654         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1655         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1656                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1657
1658         // During open, we don't have a "counterparty channel reserve" to check against, so that
1659         // requirement only comes into play on the open_channel handling side.
1660         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1661         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1662         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1663         open_channel_msg.push_msat += 1;
1664         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1665
1666         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1667         assert_eq!(msg_events.len(), 1);
1668         match msg_events[0] {
1669                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1670                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1671                 },
1672                 _ => panic!("Unexpected event"),
1673         }
1674 }
1675
1676 #[test]
1677 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1678         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1679         // calculating our counterparty's commitment transaction fee (this was previously broken).
1680         let chanmon_cfgs = create_chanmon_cfgs(2);
1681         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1682         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1683         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1684         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1685
1686         let payment_amt = 46000; // Dust amount
1687         // In the previous code, these first four payments would succeed.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692
1693         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1694         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1697         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699
1700         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1701         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1702         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1703         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1704 }
1705
1706 #[test]
1707 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1708         let chanmon_cfgs = create_chanmon_cfgs(3);
1709         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1710         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1711         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1712         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1713         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1714
1715         let feemsat = 239;
1716         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1717         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1718         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1719         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1720
1721         // Add a 2* and +1 for the fee spike reserve.
1722         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1723         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;
1724         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1725
1726         // Add a pending HTLC.
1727         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1728         let payment_event_1 = {
1729                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1730                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1731                 check_added_monitors!(nodes[0], 1);
1732
1733                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1734                 assert_eq!(events.len(), 1);
1735                 SendEvent::from_event(events.remove(0))
1736         };
1737         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1738
1739         // Attempt to trigger a channel reserve violation --> payment failure.
1740         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1741         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;
1742         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1743         let mut route_2 = route_1.clone();
1744         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1745
1746         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1747         let secp_ctx = Secp256k1::new();
1748         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1749         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1750         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1751         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1752                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1753         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1754         let msg = msgs::UpdateAddHTLC {
1755                 channel_id: chan.2,
1756                 htlc_id: 1,
1757                 amount_msat: htlc_msat + 1,
1758                 payment_hash: our_payment_hash_1,
1759                 cltv_expiry: htlc_cltv,
1760                 onion_routing_packet: onion_packet,
1761         };
1762
1763         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1764         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1765         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1766         assert_eq!(nodes[1].node.list_channels().len(), 1);
1767         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1768         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1769         check_added_monitors!(nodes[1], 1);
1770         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1771 }
1772
1773 #[test]
1774 fn test_inbound_outbound_capacity_is_not_zero() {
1775         let chanmon_cfgs = create_chanmon_cfgs(2);
1776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1778         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1779         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1780         let channels0 = node_chanmgrs[0].list_channels();
1781         let channels1 = node_chanmgrs[1].list_channels();
1782         let default_config = UserConfig::default();
1783         assert_eq!(channels0.len(), 1);
1784         assert_eq!(channels1.len(), 1);
1785
1786         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1787         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1788         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1789
1790         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1791         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1792 }
1793
1794 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1795         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1796 }
1797
1798 #[test]
1799 fn test_channel_reserve_holding_cell_htlcs() {
1800         let chanmon_cfgs = create_chanmon_cfgs(3);
1801         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1802         // When this test was written, the default base fee floated based on the HTLC count.
1803         // It is now fixed, so we simply set the fee to the expected value here.
1804         let mut config = test_default_channel_config();
1805         config.channel_config.forwarding_fee_base_msat = 239;
1806         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1807         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1808         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1809         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1810
1811         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1812         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1813
1814         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1815         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1816
1817         macro_rules! expect_forward {
1818                 ($node: expr) => {{
1819                         let mut events = $node.node.get_and_clear_pending_msg_events();
1820                         assert_eq!(events.len(), 1);
1821                         check_added_monitors!($node, 1);
1822                         let payment_event = SendEvent::from_event(events.remove(0));
1823                         payment_event
1824                 }}
1825         }
1826
1827         let feemsat = 239; // set above
1828         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1829         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1830         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1831
1832         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1833
1834         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1835         {
1836                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1837                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1838                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1839                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1840                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1841
1842                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1843                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1844                         ), true, APIError::ChannelUnavailable { .. }, {});
1845                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1846         }
1847
1848         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1849         // nodes[0]'s wealth
1850         loop {
1851                 let amt_msat = recv_value_0 + total_fee_msat;
1852                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1853                 // Also, ensure that each payment has enough to be over the dust limit to
1854                 // ensure it'll be included in each commit tx fee calculation.
1855                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1856                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1857                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1858                         break;
1859                 }
1860
1861                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1862                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1863                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1864                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1865                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1866
1867                 let (stat01_, stat11_, stat12_, stat22_) = (
1868                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1869                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1870                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1871                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1872                 );
1873
1874                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1875                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1876                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1877                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1878                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1879         }
1880
1881         // adding pending output.
1882         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1883         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1884         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1885         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1886         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1887         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1888         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1889         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1890         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1891         // policy.
1892         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1893         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1894         let amt_msat_1 = recv_value_1 + total_fee_msat;
1895
1896         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);
1897         let payment_event_1 = {
1898                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1899                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1900                 check_added_monitors!(nodes[0], 1);
1901
1902                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1903                 assert_eq!(events.len(), 1);
1904                 SendEvent::from_event(events.remove(0))
1905         };
1906         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1907
1908         // channel reserve test with htlc pending output > 0
1909         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1910         {
1911                 let mut route = route_1.clone();
1912                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1913                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1914                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1915                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1916                         ), true, APIError::ChannelUnavailable { .. }, {});
1917                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1918         }
1919
1920         // split the rest to test holding cell
1921         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1922         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1923         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1924         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1925         {
1926                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1927                 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);
1928         }
1929
1930         // now see if they go through on both sides
1931         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);
1932         // but this will stuck in the holding cell
1933         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1934                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1935         check_added_monitors!(nodes[0], 0);
1936         let events = nodes[0].node.get_and_clear_pending_events();
1937         assert_eq!(events.len(), 0);
1938
1939         // test with outbound holding cell amount > 0
1940         {
1941                 let (mut route, our_payment_hash, _, our_payment_secret) =
1942                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1943                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1944                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1945                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1946                         ), true, APIError::ChannelUnavailable { .. }, {});
1947                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1948         }
1949
1950         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);
1951         // this will also stuck in the holding cell
1952         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1953                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1954         check_added_monitors!(nodes[0], 0);
1955         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1956         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1957
1958         // flush the pending htlc
1959         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1960         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1961         check_added_monitors!(nodes[1], 1);
1962
1963         // the pending htlc should be promoted to committed
1964         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1965         check_added_monitors!(nodes[0], 1);
1966         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1967
1968         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1969         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1970         // No commitment_signed so get_event_msg's assert(len == 1) passes
1971         check_added_monitors!(nodes[0], 1);
1972
1973         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1974         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1975         check_added_monitors!(nodes[1], 1);
1976
1977         expect_pending_htlcs_forwardable!(nodes[1]);
1978
1979         let ref payment_event_11 = expect_forward!(nodes[1]);
1980         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1981         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1982
1983         expect_pending_htlcs_forwardable!(nodes[2]);
1984         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1985
1986         // flush the htlcs in the holding cell
1987         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1988         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1989         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1990         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1991         expect_pending_htlcs_forwardable!(nodes[1]);
1992
1993         let ref payment_event_3 = expect_forward!(nodes[1]);
1994         assert_eq!(payment_event_3.msgs.len(), 2);
1995         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1996         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1997
1998         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1999         expect_pending_htlcs_forwardable!(nodes[2]);
2000
2001         let events = nodes[2].node.get_and_clear_pending_events();
2002         assert_eq!(events.len(), 2);
2003         match events[0] {
2004                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2005                         assert_eq!(our_payment_hash_21, *payment_hash);
2006                         assert_eq!(recv_value_21, amount_msat);
2007                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2008                         assert_eq!(via_channel_id, Some(chan_2.2));
2009                         match &purpose {
2010                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2011                                         assert!(payment_preimage.is_none());
2012                                         assert_eq!(our_payment_secret_21, *payment_secret);
2013                                 },
2014                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2015                         }
2016                 },
2017                 _ => panic!("Unexpected event"),
2018         }
2019         match events[1] {
2020                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2021                         assert_eq!(our_payment_hash_22, *payment_hash);
2022                         assert_eq!(recv_value_22, amount_msat);
2023                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2024                         assert_eq!(via_channel_id, Some(chan_2.2));
2025                         match &purpose {
2026                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2027                                         assert!(payment_preimage.is_none());
2028                                         assert_eq!(our_payment_secret_22, *payment_secret);
2029                                 },
2030                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2031                         }
2032                 },
2033                 _ => panic!("Unexpected event"),
2034         }
2035
2036         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2037         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2038         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2039
2040         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2041         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2042         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2043
2044         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2045         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);
2046         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2047         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2048         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2049
2050         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2051         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2052 }
2053
2054 #[test]
2055 fn channel_reserve_in_flight_removes() {
2056         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2057         // can send to its counterparty, but due to update ordering, the other side may not yet have
2058         // considered those HTLCs fully removed.
2059         // This tests that we don't count HTLCs which will not be included in the next remote
2060         // commitment transaction towards the reserve value (as it implies no commitment transaction
2061         // will be generated which violates the remote reserve value).
2062         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2063         // To test this we:
2064         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2065         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2066         //    you only consider the value of the first HTLC, it may not),
2067         //  * start routing a third HTLC from A to B,
2068         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2069         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2070         //  * deliver the first fulfill from B
2071         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2072         //    claim,
2073         //  * deliver A's response CS and RAA.
2074         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2075         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2076         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2077         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2078         let chanmon_cfgs = create_chanmon_cfgs(2);
2079         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2080         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2081         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2082         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2083
2084         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2085         // Route the first two HTLCs.
2086         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2087         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2088         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2089
2090         // Start routing the third HTLC (this is just used to get everyone in the right state).
2091         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2092         let send_1 = {
2093                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2094                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2095                 check_added_monitors!(nodes[0], 1);
2096                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2097                 assert_eq!(events.len(), 1);
2098                 SendEvent::from_event(events.remove(0))
2099         };
2100
2101         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2102         // initial fulfill/CS.
2103         nodes[1].node.claim_funds(payment_preimage_1);
2104         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2105         check_added_monitors!(nodes[1], 1);
2106         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2107
2108         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2109         // remove the second HTLC when we send the HTLC back from B to A.
2110         nodes[1].node.claim_funds(payment_preimage_2);
2111         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2112         check_added_monitors!(nodes[1], 1);
2113         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2114
2115         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2116         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2117         check_added_monitors!(nodes[0], 1);
2118         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2119         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2120
2121         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2122         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2123         check_added_monitors!(nodes[1], 1);
2124         // B is already AwaitingRAA, so cant generate a CS here
2125         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2126
2127         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2128         check_added_monitors!(nodes[1], 1);
2129         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2130
2131         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2132         check_added_monitors!(nodes[0], 1);
2133         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2134
2135         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2136         check_added_monitors!(nodes[1], 1);
2137         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2138
2139         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2140         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2141         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2142         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2143         // on-chain as necessary).
2144         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2145         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2146         check_added_monitors!(nodes[0], 1);
2147         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2148         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2149
2150         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2151         check_added_monitors!(nodes[1], 1);
2152         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2153
2154         expect_pending_htlcs_forwardable!(nodes[1]);
2155         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2156
2157         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2158         // resolve the second HTLC from A's point of view.
2159         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160         check_added_monitors!(nodes[0], 1);
2161         expect_payment_path_successful!(nodes[0]);
2162         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2163
2164         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2165         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2166         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2167         let send_2 = {
2168                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2169                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2170                 check_added_monitors!(nodes[1], 1);
2171                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2172                 assert_eq!(events.len(), 1);
2173                 SendEvent::from_event(events.remove(0))
2174         };
2175
2176         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2177         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2178         check_added_monitors!(nodes[0], 1);
2179         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2180
2181         // Now just resolve all the outstanding messages/HTLCs for completeness...
2182
2183         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2184         check_added_monitors!(nodes[1], 1);
2185         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2186
2187         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2188         check_added_monitors!(nodes[1], 1);
2189
2190         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2191         check_added_monitors!(nodes[0], 1);
2192         expect_payment_path_successful!(nodes[0]);
2193         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2194
2195         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2196         check_added_monitors!(nodes[1], 1);
2197         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2198
2199         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2200         check_added_monitors!(nodes[0], 1);
2201
2202         expect_pending_htlcs_forwardable!(nodes[0]);
2203         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2204
2205         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2206         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2207 }
2208
2209 #[test]
2210 fn channel_monitor_network_test() {
2211         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2212         // tests that ChannelMonitor is able to recover from various states.
2213         let chanmon_cfgs = create_chanmon_cfgs(5);
2214         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2215         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2216         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2217
2218         // Create some initial channels
2219         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2220         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2221         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2222         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2223
2224         // Make sure all nodes are at the same starting height
2225         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2226         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2227         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2228         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2229         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2230
2231         // Rebalance the network a bit by relaying one payment through all the channels...
2232         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2233         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2234         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2235         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2236
2237         // Simple case with no pending HTLCs:
2238         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2239         check_added_monitors!(nodes[1], 1);
2240         check_closed_broadcast!(nodes[1], true);
2241         {
2242                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2243                 assert_eq!(node_txn.len(), 1);
2244                 mine_transaction(&nodes[0], &node_txn[0]);
2245                 check_added_monitors!(nodes[0], 1);
2246                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2247         }
2248         check_closed_broadcast!(nodes[0], true);
2249         assert_eq!(nodes[0].node.list_channels().len(), 0);
2250         assert_eq!(nodes[1].node.list_channels().len(), 1);
2251         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2252         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2253
2254         // One pending HTLC is discarded by the force-close:
2255         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2256
2257         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2258         // broadcasted until we reach the timelock time).
2259         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2260         check_closed_broadcast!(nodes[1], true);
2261         check_added_monitors!(nodes[1], 1);
2262         {
2263                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2264                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2265                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2266                 mine_transaction(&nodes[2], &node_txn[0]);
2267                 check_added_monitors!(nodes[2], 1);
2268                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2269         }
2270         check_closed_broadcast!(nodes[2], true);
2271         assert_eq!(nodes[1].node.list_channels().len(), 0);
2272         assert_eq!(nodes[2].node.list_channels().len(), 1);
2273         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2274         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2275
2276         macro_rules! claim_funds {
2277                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2278                         {
2279                                 $node.node.claim_funds($preimage);
2280                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2281                                 check_added_monitors!($node, 1);
2282
2283                                 let events = $node.node.get_and_clear_pending_msg_events();
2284                                 assert_eq!(events.len(), 1);
2285                                 match events[0] {
2286                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2287                                                 assert!(update_add_htlcs.is_empty());
2288                                                 assert!(update_fail_htlcs.is_empty());
2289                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2290                                         },
2291                                         _ => panic!("Unexpected event"),
2292                                 };
2293                         }
2294                 }
2295         }
2296
2297         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2298         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2299         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2300         check_added_monitors!(nodes[2], 1);
2301         check_closed_broadcast!(nodes[2], true);
2302         let node2_commitment_txid;
2303         {
2304                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2305                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2306                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2307                 node2_commitment_txid = node_txn[0].txid();
2308
2309                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2310                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2311                 mine_transaction(&nodes[3], &node_txn[0]);
2312                 check_added_monitors!(nodes[3], 1);
2313                 check_preimage_claim(&nodes[3], &node_txn);
2314         }
2315         check_closed_broadcast!(nodes[3], true);
2316         assert_eq!(nodes[2].node.list_channels().len(), 0);
2317         assert_eq!(nodes[3].node.list_channels().len(), 1);
2318         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2319         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2320
2321         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2322         // confusing us in the following tests.
2323         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2324
2325         // One pending HTLC to time out:
2326         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2327         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2328         // buffer space).
2329
2330         let (close_chan_update_1, close_chan_update_2) = {
2331                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2332                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2333                 assert_eq!(events.len(), 2);
2334                 let close_chan_update_1 = match events[0] {
2335                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2336                                 msg.clone()
2337                         },
2338                         _ => panic!("Unexpected event"),
2339                 };
2340                 match events[1] {
2341                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2342                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2343                         },
2344                         _ => panic!("Unexpected event"),
2345                 }
2346                 check_added_monitors!(nodes[3], 1);
2347
2348                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2349                 {
2350                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2351                         node_txn.retain(|tx| {
2352                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2353                                         false
2354                                 } else { true }
2355                         });
2356                 }
2357
2358                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2359
2360                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2361                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2362
2363                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2364                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2365                 assert_eq!(events.len(), 2);
2366                 let close_chan_update_2 = match events[0] {
2367                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2368                                 msg.clone()
2369                         },
2370                         _ => panic!("Unexpected event"),
2371                 };
2372                 match events[1] {
2373                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2374                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2375                         },
2376                         _ => panic!("Unexpected event"),
2377                 }
2378                 check_added_monitors!(nodes[4], 1);
2379                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2380
2381                 mine_transaction(&nodes[4], &node_txn[0]);
2382                 check_preimage_claim(&nodes[4], &node_txn);
2383                 (close_chan_update_1, close_chan_update_2)
2384         };
2385         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2386         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2387         assert_eq!(nodes[3].node.list_channels().len(), 0);
2388         assert_eq!(nodes[4].node.list_channels().len(), 0);
2389
2390         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2391                 ChannelMonitorUpdateStatus::Completed);
2392         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2393         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2394 }
2395
2396 #[test]
2397 fn test_justice_tx_htlc_timeout() {
2398         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2399         let mut alice_config = UserConfig::default();
2400         alice_config.channel_handshake_config.announced_channel = true;
2401         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2402         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2403         let mut bob_config = UserConfig::default();
2404         bob_config.channel_handshake_config.announced_channel = true;
2405         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2406         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2407         let user_cfgs = [Some(alice_config), Some(bob_config)];
2408         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2409         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2410         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2413         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2414         // Create some new channels:
2415         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2416
2417         // A pending HTLC which will be revoked:
2418         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2419         // Get the will-be-revoked local txn from nodes[0]
2420         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2421         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2422         assert_eq!(revoked_local_txn[0].input.len(), 1);
2423         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2424         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2425         assert_eq!(revoked_local_txn[1].input.len(), 1);
2426         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2427         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2428         // Revoke the old state
2429         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2430
2431         {
2432                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2433                 {
2434                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2435                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2436                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2437                         check_spends!(node_txn[0], revoked_local_txn[0]);
2438                         node_txn.swap_remove(0);
2439                 }
2440                 check_added_monitors!(nodes[1], 1);
2441                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2442                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2443
2444                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2445                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2446                 // Verify broadcast of revoked HTLC-timeout
2447                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2448                 check_added_monitors!(nodes[0], 1);
2449                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2450                 // Broadcast revoked HTLC-timeout on node 1
2451                 mine_transaction(&nodes[1], &node_txn[1]);
2452                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2453         }
2454         get_announce_close_broadcast_events(&nodes, 0, 1);
2455         assert_eq!(nodes[0].node.list_channels().len(), 0);
2456         assert_eq!(nodes[1].node.list_channels().len(), 0);
2457 }
2458
2459 #[test]
2460 fn test_justice_tx_htlc_success() {
2461         // Test justice txn built on revoked HTLC-Success tx, against both sides
2462         let mut alice_config = UserConfig::default();
2463         alice_config.channel_handshake_config.announced_channel = true;
2464         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2465         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2466         let mut bob_config = UserConfig::default();
2467         bob_config.channel_handshake_config.announced_channel = true;
2468         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2469         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2470         let user_cfgs = [Some(alice_config), Some(bob_config)];
2471         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2472         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2473         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2476         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2477         // Create some new channels:
2478         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2479
2480         // A pending HTLC which will be revoked:
2481         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2482         // Get the will-be-revoked local txn from B
2483         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2484         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2485         assert_eq!(revoked_local_txn[0].input.len(), 1);
2486         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2487         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2488         // Revoke the old state
2489         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2490         {
2491                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2492                 {
2493                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2494                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2495                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2496
2497                         check_spends!(node_txn[0], revoked_local_txn[0]);
2498                         node_txn.swap_remove(0);
2499                 }
2500                 check_added_monitors!(nodes[0], 1);
2501                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2502
2503                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2504                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2505                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2506                 check_added_monitors!(nodes[1], 1);
2507                 mine_transaction(&nodes[0], &node_txn[1]);
2508                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2509                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2510         }
2511         get_announce_close_broadcast_events(&nodes, 0, 1);
2512         assert_eq!(nodes[0].node.list_channels().len(), 0);
2513         assert_eq!(nodes[1].node.list_channels().len(), 0);
2514 }
2515
2516 #[test]
2517 fn revoked_output_claim() {
2518         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2519         // transaction is broadcast by its counterparty
2520         let chanmon_cfgs = create_chanmon_cfgs(2);
2521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2523         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2524         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2525         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2526         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2527         assert_eq!(revoked_local_txn.len(), 1);
2528         // Only output is the full channel value back to nodes[0]:
2529         assert_eq!(revoked_local_txn[0].output.len(), 1);
2530         // Send a payment through, updating everyone's latest commitment txn
2531         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2532
2533         // Inform nodes[1] that nodes[0] broadcast a stale tx
2534         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535         check_added_monitors!(nodes[1], 1);
2536         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2537         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2538         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2539
2540         check_spends!(node_txn[0], revoked_local_txn[0]);
2541
2542         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2543         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2544         get_announce_close_broadcast_events(&nodes, 0, 1);
2545         check_added_monitors!(nodes[0], 1);
2546         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2547 }
2548
2549 #[test]
2550 fn claim_htlc_outputs_shared_tx() {
2551         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2552         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2553         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2554         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2555         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2556         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2557
2558         // Create some new channel:
2559         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2560
2561         // Rebalance the network to generate htlc in the two directions
2562         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2563         // 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
2564         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2565         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2566
2567         // Get the will-be-revoked local txn from node[0]
2568         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2569         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2570         assert_eq!(revoked_local_txn[0].input.len(), 1);
2571         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2572         assert_eq!(revoked_local_txn[1].input.len(), 1);
2573         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2574         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2575         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2576
2577         //Revoke the old state
2578         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2579
2580         {
2581                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2582                 check_added_monitors!(nodes[0], 1);
2583                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2584                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2585                 check_added_monitors!(nodes[1], 1);
2586                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2587                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2588                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2589
2590                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2591                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2592
2593                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2594                 check_spends!(node_txn[0], revoked_local_txn[0]);
2595
2596                 let mut witness_lens = BTreeSet::new();
2597                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2598                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2599                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2600                 assert_eq!(witness_lens.len(), 3);
2601                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2602                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2603                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2604
2605                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2606                 // ANTI_REORG_DELAY confirmations.
2607                 mine_transaction(&nodes[1], &node_txn[0]);
2608                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2609                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2610         }
2611         get_announce_close_broadcast_events(&nodes, 0, 1);
2612         assert_eq!(nodes[0].node.list_channels().len(), 0);
2613         assert_eq!(nodes[1].node.list_channels().len(), 0);
2614 }
2615
2616 #[test]
2617 fn claim_htlc_outputs_single_tx() {
2618         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2619         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2620         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2623         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2624
2625         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2626
2627         // Rebalance the network to generate htlc in the two directions
2628         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2629         // 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
2630         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2631         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2632         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2633
2634         // Get the will-be-revoked local txn from node[0]
2635         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2636
2637         //Revoke the old state
2638         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2639
2640         {
2641                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2642                 check_added_monitors!(nodes[0], 1);
2643                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2644                 check_added_monitors!(nodes[1], 1);
2645                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2646                 let mut events = nodes[0].node.get_and_clear_pending_events();
2647                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2648                 match events.last().unwrap() {
2649                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2650                         _ => panic!("Unexpected event"),
2651                 }
2652
2653                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2654                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2655
2656                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2657
2658                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2659                 assert_eq!(node_txn[0].input.len(), 1);
2660                 check_spends!(node_txn[0], chan_1.3);
2661                 assert_eq!(node_txn[1].input.len(), 1);
2662                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2663                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2664                 check_spends!(node_txn[1], node_txn[0]);
2665
2666                 // Filter out any non justice transactions.
2667                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2668                 assert!(node_txn.len() > 3);
2669
2670                 assert_eq!(node_txn[0].input.len(), 1);
2671                 assert_eq!(node_txn[1].input.len(), 1);
2672                 assert_eq!(node_txn[2].input.len(), 1);
2673
2674                 check_spends!(node_txn[0], revoked_local_txn[0]);
2675                 check_spends!(node_txn[1], revoked_local_txn[0]);
2676                 check_spends!(node_txn[2], revoked_local_txn[0]);
2677
2678                 let mut witness_lens = BTreeSet::new();
2679                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2680                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2681                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2682                 assert_eq!(witness_lens.len(), 3);
2683                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2684                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2685                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2686
2687                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2688                 // ANTI_REORG_DELAY confirmations.
2689                 mine_transaction(&nodes[1], &node_txn[0]);
2690                 mine_transaction(&nodes[1], &node_txn[1]);
2691                 mine_transaction(&nodes[1], &node_txn[2]);
2692                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2693                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2694         }
2695         get_announce_close_broadcast_events(&nodes, 0, 1);
2696         assert_eq!(nodes[0].node.list_channels().len(), 0);
2697         assert_eq!(nodes[1].node.list_channels().len(), 0);
2698 }
2699
2700 #[test]
2701 fn test_htlc_on_chain_success() {
2702         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2703         // the preimage backward accordingly. So here we test that ChannelManager is
2704         // broadcasting the right event to other nodes in payment path.
2705         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2706         // A --------------------> B ----------------------> C (preimage)
2707         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2708         // commitment transaction was broadcast.
2709         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2710         // towards B.
2711         // B should be able to claim via preimage if A then broadcasts its local tx.
2712         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2713         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2714         // PaymentSent event).
2715
2716         let chanmon_cfgs = create_chanmon_cfgs(3);
2717         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2718         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2719         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2720
2721         // Create some initial channels
2722         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2723         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2724
2725         // Ensure all nodes are at the same height
2726         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2727         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2728         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2729         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2730
2731         // Rebalance the network a bit by relaying one payment through all the channels...
2732         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2733         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2734
2735         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2736         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2737
2738         // Broadcast legit commitment tx from C on B's chain
2739         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2740         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2741         assert_eq!(commitment_tx.len(), 1);
2742         check_spends!(commitment_tx[0], chan_2.3);
2743         nodes[2].node.claim_funds(our_payment_preimage);
2744         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2745         nodes[2].node.claim_funds(our_payment_preimage_2);
2746         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2747         check_added_monitors!(nodes[2], 2);
2748         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2749         assert!(updates.update_add_htlcs.is_empty());
2750         assert!(updates.update_fail_htlcs.is_empty());
2751         assert!(updates.update_fail_malformed_htlcs.is_empty());
2752         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2753
2754         mine_transaction(&nodes[2], &commitment_tx[0]);
2755         check_closed_broadcast!(nodes[2], true);
2756         check_added_monitors!(nodes[2], 1);
2757         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2758         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2759         assert_eq!(node_txn.len(), 2);
2760         check_spends!(node_txn[0], commitment_tx[0]);
2761         check_spends!(node_txn[1], commitment_tx[0]);
2762         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2763         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2764         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2765         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2766         assert_eq!(node_txn[0].lock_time.0, 0);
2767         assert_eq!(node_txn[1].lock_time.0, 0);
2768
2769         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2770         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()]));
2771         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2772         {
2773                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2774                 assert_eq!(added_monitors.len(), 1);
2775                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2776                 added_monitors.clear();
2777         }
2778         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2779         assert_eq!(forwarded_events.len(), 3);
2780         match forwarded_events[0] {
2781                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2782                 _ => panic!("Unexpected event"),
2783         }
2784         let chan_id = Some(chan_1.2);
2785         match forwarded_events[1] {
2786                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2787                         assert_eq!(fee_earned_msat, Some(1000));
2788                         assert_eq!(prev_channel_id, chan_id);
2789                         assert_eq!(claim_from_onchain_tx, true);
2790                         assert_eq!(next_channel_id, Some(chan_2.2));
2791                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2792                 },
2793                 _ => panic!()
2794         }
2795         match forwarded_events[2] {
2796                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2797                         assert_eq!(fee_earned_msat, Some(1000));
2798                         assert_eq!(prev_channel_id, chan_id);
2799                         assert_eq!(claim_from_onchain_tx, true);
2800                         assert_eq!(next_channel_id, Some(chan_2.2));
2801                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2802                 },
2803                 _ => panic!()
2804         }
2805         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2806         {
2807                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2808                 assert_eq!(added_monitors.len(), 2);
2809                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2810                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2811                 added_monitors.clear();
2812         }
2813         assert_eq!(events.len(), 3);
2814
2815         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2816         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2817
2818         match nodes_2_event {
2819                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2820                 _ => panic!("Unexpected event"),
2821         }
2822
2823         match nodes_0_event {
2824                 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, .. } } => {
2825                         assert!(update_add_htlcs.is_empty());
2826                         assert!(update_fail_htlcs.is_empty());
2827                         assert_eq!(update_fulfill_htlcs.len(), 1);
2828                         assert!(update_fail_malformed_htlcs.is_empty());
2829                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2830                 },
2831                 _ => panic!("Unexpected event"),
2832         };
2833
2834         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2835         match events[0] {
2836                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2837                 _ => panic!("Unexpected event"),
2838         }
2839
2840         macro_rules! check_tx_local_broadcast {
2841                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2842                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2843                         assert_eq!(node_txn.len(), 2);
2844                         // Node[1]: 2 * HTLC-timeout tx
2845                         // Node[0]: 2 * HTLC-timeout tx
2846                         check_spends!(node_txn[0], $commitment_tx);
2847                         check_spends!(node_txn[1], $commitment_tx);
2848                         assert_ne!(node_txn[0].lock_time.0, 0);
2849                         assert_ne!(node_txn[1].lock_time.0, 0);
2850                         if $htlc_offered {
2851                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2852                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2854                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2855                         } else {
2856                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2857                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2858                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2859                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2860                         }
2861                         node_txn.clear();
2862                 } }
2863         }
2864         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2865         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2866
2867         // Broadcast legit commitment tx from A on B's chain
2868         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2869         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2870         check_spends!(node_a_commitment_tx[0], chan_1.3);
2871         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2872         check_closed_broadcast!(nodes[1], true);
2873         check_added_monitors!(nodes[1], 1);
2874         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2875         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2876         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2877         let commitment_spend =
2878                 if node_txn.len() == 1 {
2879                         &node_txn[0]
2880                 } else {
2881                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2882                         // FullBlockViaListen
2883                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2884                                 check_spends!(node_txn[1], commitment_tx[0]);
2885                                 check_spends!(node_txn[2], commitment_tx[0]);
2886                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2887                                 &node_txn[0]
2888                         } else {
2889                                 check_spends!(node_txn[0], commitment_tx[0]);
2890                                 check_spends!(node_txn[1], commitment_tx[0]);
2891                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2892                                 &node_txn[2]
2893                         }
2894                 };
2895
2896         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2897         assert_eq!(commitment_spend.input.len(), 2);
2898         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2899         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2900         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2901         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2902         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2903         // we already checked the same situation with A.
2904
2905         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2906         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2907         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2908         check_closed_broadcast!(nodes[0], true);
2909         check_added_monitors!(nodes[0], 1);
2910         let events = nodes[0].node.get_and_clear_pending_events();
2911         assert_eq!(events.len(), 5);
2912         let mut first_claimed = false;
2913         for event in events {
2914                 match event {
2915                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2916                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2917                                         assert!(!first_claimed);
2918                                         first_claimed = true;
2919                                 } else {
2920                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2921                                         assert_eq!(payment_hash, payment_hash_2);
2922                                 }
2923                         },
2924                         Event::PaymentPathSuccessful { .. } => {},
2925                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2926                         _ => panic!("Unexpected event"),
2927                 }
2928         }
2929         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2930 }
2931
2932 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2933         // Test that in case of a unilateral close onchain, we detect the state of output and
2934         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2935         // broadcasting the right event to other nodes in payment path.
2936         // A ------------------> B ----------------------> C (timeout)
2937         //    B's commitment tx                 C's commitment tx
2938         //            \                                  \
2939         //         B's HTLC timeout tx               B's timeout tx
2940
2941         let chanmon_cfgs = create_chanmon_cfgs(3);
2942         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2943         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2944         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2945         *nodes[0].connect_style.borrow_mut() = connect_style;
2946         *nodes[1].connect_style.borrow_mut() = connect_style;
2947         *nodes[2].connect_style.borrow_mut() = connect_style;
2948
2949         // Create some intial channels
2950         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2951         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2952
2953         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2954         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2955         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2956
2957         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2958
2959         // Broadcast legit commitment tx from C on B's chain
2960         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2961         check_spends!(commitment_tx[0], chan_2.3);
2962         nodes[2].node.fail_htlc_backwards(&payment_hash);
2963         check_added_monitors!(nodes[2], 0);
2964         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2965         check_added_monitors!(nodes[2], 1);
2966
2967         let events = nodes[2].node.get_and_clear_pending_msg_events();
2968         assert_eq!(events.len(), 1);
2969         match events[0] {
2970                 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, .. } } => {
2971                         assert!(update_add_htlcs.is_empty());
2972                         assert!(!update_fail_htlcs.is_empty());
2973                         assert!(update_fulfill_htlcs.is_empty());
2974                         assert!(update_fail_malformed_htlcs.is_empty());
2975                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2976                 },
2977                 _ => panic!("Unexpected event"),
2978         };
2979         mine_transaction(&nodes[2], &commitment_tx[0]);
2980         check_closed_broadcast!(nodes[2], true);
2981         check_added_monitors!(nodes[2], 1);
2982         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2983         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2984         assert_eq!(node_txn.len(), 0);
2985
2986         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2987         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2988         mine_transaction(&nodes[1], &commitment_tx[0]);
2989         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2990         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2991         let timeout_tx = {
2992                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2993                 if nodes[1].connect_style.borrow().skips_blocks() {
2994                         assert_eq!(txn.len(), 1);
2995                 } else {
2996                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2997                 }
2998                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2999                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3000                 txn.remove(0)
3001         };
3002
3003         mine_transaction(&nodes[1], &timeout_tx);
3004         check_added_monitors!(nodes[1], 1);
3005         check_closed_broadcast!(nodes[1], true);
3006
3007         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3008
3009         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 }]);
3010         check_added_monitors!(nodes[1], 1);
3011         let events = nodes[1].node.get_and_clear_pending_msg_events();
3012         assert_eq!(events.len(), 1);
3013         match events[0] {
3014                 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, .. } } => {
3015                         assert!(update_add_htlcs.is_empty());
3016                         assert!(!update_fail_htlcs.is_empty());
3017                         assert!(update_fulfill_htlcs.is_empty());
3018                         assert!(update_fail_malformed_htlcs.is_empty());
3019                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3020                 },
3021                 _ => panic!("Unexpected event"),
3022         };
3023
3024         // Broadcast legit commitment tx from B on A's chain
3025         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3026         check_spends!(commitment_tx[0], chan_1.3);
3027
3028         mine_transaction(&nodes[0], &commitment_tx[0]);
3029         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3030
3031         check_closed_broadcast!(nodes[0], true);
3032         check_added_monitors!(nodes[0], 1);
3033         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3034         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3035         assert_eq!(node_txn.len(), 1);
3036         check_spends!(node_txn[0], commitment_tx[0]);
3037         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3038 }
3039
3040 #[test]
3041 fn test_htlc_on_chain_timeout() {
3042         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3043         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3044         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3045 }
3046
3047 #[test]
3048 fn test_simple_commitment_revoked_fail_backward() {
3049         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3050         // and fail backward accordingly.
3051
3052         let chanmon_cfgs = create_chanmon_cfgs(3);
3053         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3054         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3055         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3056
3057         // Create some initial channels
3058         create_announced_chan_between_nodes(&nodes, 0, 1);
3059         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3060
3061         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3062         // Get the will-be-revoked local txn from nodes[2]
3063         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3064         // Revoke the old state
3065         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3066
3067         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3068
3069         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3070         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3071         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3072         check_added_monitors!(nodes[1], 1);
3073         check_closed_broadcast!(nodes[1], true);
3074
3075         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 }]);
3076         check_added_monitors!(nodes[1], 1);
3077         let events = nodes[1].node.get_and_clear_pending_msg_events();
3078         assert_eq!(events.len(), 1);
3079         match events[0] {
3080                 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, .. } } => {
3081                         assert!(update_add_htlcs.is_empty());
3082                         assert_eq!(update_fail_htlcs.len(), 1);
3083                         assert!(update_fulfill_htlcs.is_empty());
3084                         assert!(update_fail_malformed_htlcs.is_empty());
3085                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3086
3087                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3088                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3089                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3090                 },
3091                 _ => panic!("Unexpected event"),
3092         }
3093 }
3094
3095 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3096         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3097         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3098         // commitment transaction anymore.
3099         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3100         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3101         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3102         // technically disallowed and we should probably handle it reasonably.
3103         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3104         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3105         // transactions:
3106         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3107         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3108         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3109         //   and once they revoke the previous commitment transaction (allowing us to send a new
3110         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3111         let chanmon_cfgs = create_chanmon_cfgs(3);
3112         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3113         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3114         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3115
3116         // Create some initial channels
3117         create_announced_chan_between_nodes(&nodes, 0, 1);
3118         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3119
3120         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 });
3121         // Get the will-be-revoked local txn from nodes[2]
3122         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3123         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3124         // Revoke the old state
3125         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3126
3127         let value = if use_dust {
3128                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3129                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3130                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3131                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3132         } else { 3000000 };
3133
3134         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3135         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3136         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3137
3138         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3139         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3140         check_added_monitors!(nodes[2], 1);
3141         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3142         assert!(updates.update_add_htlcs.is_empty());
3143         assert!(updates.update_fulfill_htlcs.is_empty());
3144         assert!(updates.update_fail_malformed_htlcs.is_empty());
3145         assert_eq!(updates.update_fail_htlcs.len(), 1);
3146         assert!(updates.update_fee.is_none());
3147         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3148         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3149         // Drop the last RAA from 3 -> 2
3150
3151         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3152         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3153         check_added_monitors!(nodes[2], 1);
3154         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3155         assert!(updates.update_add_htlcs.is_empty());
3156         assert!(updates.update_fulfill_htlcs.is_empty());
3157         assert!(updates.update_fail_malformed_htlcs.is_empty());
3158         assert_eq!(updates.update_fail_htlcs.len(), 1);
3159         assert!(updates.update_fee.is_none());
3160         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3161         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3162         check_added_monitors!(nodes[1], 1);
3163         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3164         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3165         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3166         check_added_monitors!(nodes[2], 1);
3167
3168         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3169         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3170         check_added_monitors!(nodes[2], 1);
3171         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3172         assert!(updates.update_add_htlcs.is_empty());
3173         assert!(updates.update_fulfill_htlcs.is_empty());
3174         assert!(updates.update_fail_malformed_htlcs.is_empty());
3175         assert_eq!(updates.update_fail_htlcs.len(), 1);
3176         assert!(updates.update_fee.is_none());
3177         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3178         // At this point first_payment_hash has dropped out of the latest two commitment
3179         // transactions that nodes[1] is tracking...
3180         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3181         check_added_monitors!(nodes[1], 1);
3182         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3183         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3184         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3185         check_added_monitors!(nodes[2], 1);
3186
3187         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3188         // on nodes[2]'s RAA.
3189         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3190         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3191                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3192         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3193         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3194         check_added_monitors!(nodes[1], 0);
3195
3196         if deliver_bs_raa {
3197                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3198                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3199                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3200                 check_added_monitors!(nodes[1], 1);
3201                 let events = nodes[1].node.get_and_clear_pending_events();
3202                 assert_eq!(events.len(), 2);
3203                 match events[0] {
3204                         Event::PendingHTLCsForwardable { .. } => { },
3205                         _ => panic!("Unexpected event"),
3206                 };
3207                 match events[1] {
3208                         Event::HTLCHandlingFailed { .. } => { },
3209                         _ => panic!("Unexpected event"),
3210                 }
3211                 // Deliberately don't process the pending fail-back so they all fail back at once after
3212                 // block connection just like the !deliver_bs_raa case
3213         }
3214
3215         let mut failed_htlcs = HashSet::new();
3216         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3217
3218         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3219         check_added_monitors!(nodes[1], 1);
3220         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3221
3222         let events = nodes[1].node.get_and_clear_pending_events();
3223         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3224         match events[0] {
3225                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3226                 _ => panic!("Unexepected event"),
3227         }
3228         match events[1] {
3229                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3230                         assert_eq!(*payment_hash, fourth_payment_hash);
3231                 },
3232                 _ => panic!("Unexpected event"),
3233         }
3234         match events[2] {
3235                 Event::PaymentFailed { ref payment_hash, .. } => {
3236                         assert_eq!(*payment_hash, fourth_payment_hash);
3237                 },
3238                 _ => panic!("Unexpected event"),
3239         }
3240
3241         nodes[1].node.process_pending_htlc_forwards();
3242         check_added_monitors!(nodes[1], 1);
3243
3244         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3245         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3246
3247         if deliver_bs_raa {
3248                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3249                 match nodes_2_event {
3250                         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, .. } } => {
3251                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3252                                 assert_eq!(update_add_htlcs.len(), 1);
3253                                 assert!(update_fulfill_htlcs.is_empty());
3254                                 assert!(update_fail_htlcs.is_empty());
3255                                 assert!(update_fail_malformed_htlcs.is_empty());
3256                         },
3257                         _ => panic!("Unexpected event"),
3258                 }
3259         }
3260
3261         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3262         match nodes_2_event {
3263                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3264                         assert_eq!(channel_id, chan_2.2);
3265                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3266                 },
3267                 _ => panic!("Unexpected event"),
3268         }
3269
3270         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3271         match nodes_0_event {
3272                 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, .. } } => {
3273                         assert!(update_add_htlcs.is_empty());
3274                         assert_eq!(update_fail_htlcs.len(), 3);
3275                         assert!(update_fulfill_htlcs.is_empty());
3276                         assert!(update_fail_malformed_htlcs.is_empty());
3277                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3278
3279                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3280                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3281                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3282
3283                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3284
3285                         let events = nodes[0].node.get_and_clear_pending_events();
3286                         assert_eq!(events.len(), 6);
3287                         match events[0] {
3288                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3289                                         assert!(failed_htlcs.insert(payment_hash.0));
3290                                         // If we delivered B's RAA we got an unknown preimage error, not something
3291                                         // that we should update our routing table for.
3292                                         if !deliver_bs_raa {
3293                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3294                                         }
3295                                 },
3296                                 _ => panic!("Unexpected event"),
3297                         }
3298                         match events[1] {
3299                                 Event::PaymentFailed { ref payment_hash, .. } => {
3300                                         assert_eq!(*payment_hash, first_payment_hash);
3301                                 },
3302                                 _ => panic!("Unexpected event"),
3303                         }
3304                         match events[2] {
3305                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3306                                         assert!(failed_htlcs.insert(payment_hash.0));
3307                                 },
3308                                 _ => panic!("Unexpected event"),
3309                         }
3310                         match events[3] {
3311                                 Event::PaymentFailed { ref payment_hash, .. } => {
3312                                         assert_eq!(*payment_hash, second_payment_hash);
3313                                 },
3314                                 _ => panic!("Unexpected event"),
3315                         }
3316                         match events[4] {
3317                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3318                                         assert!(failed_htlcs.insert(payment_hash.0));
3319                                 },
3320                                 _ => panic!("Unexpected event"),
3321                         }
3322                         match events[5] {
3323                                 Event::PaymentFailed { ref payment_hash, .. } => {
3324                                         assert_eq!(*payment_hash, third_payment_hash);
3325                                 },
3326                                 _ => panic!("Unexpected event"),
3327                         }
3328                 },
3329                 _ => panic!("Unexpected event"),
3330         }
3331
3332         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3333         match events[0] {
3334                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3335                 _ => panic!("Unexpected event"),
3336         }
3337
3338         assert!(failed_htlcs.contains(&first_payment_hash.0));
3339         assert!(failed_htlcs.contains(&second_payment_hash.0));
3340         assert!(failed_htlcs.contains(&third_payment_hash.0));
3341 }
3342
3343 #[test]
3344 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3345         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3346         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3347         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3348         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3349 }
3350
3351 #[test]
3352 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3353         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3354         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3355         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3356         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3357 }
3358
3359 #[test]
3360 fn fail_backward_pending_htlc_upon_channel_failure() {
3361         let chanmon_cfgs = create_chanmon_cfgs(2);
3362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3365         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3366
3367         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3368         {
3369                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3370                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3371                         PaymentId(payment_hash.0)).unwrap();
3372                 check_added_monitors!(nodes[0], 1);
3373
3374                 let payment_event = {
3375                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3376                         assert_eq!(events.len(), 1);
3377                         SendEvent::from_event(events.remove(0))
3378                 };
3379                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3380                 assert_eq!(payment_event.msgs.len(), 1);
3381         }
3382
3383         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3384         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3385         {
3386                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3387                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3388                 check_added_monitors!(nodes[0], 0);
3389
3390                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3391         }
3392
3393         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3394         {
3395                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3396
3397                 let secp_ctx = Secp256k1::new();
3398                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3399                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3400                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3401                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3402                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3403                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3404
3405                 // Send a 0-msat update_add_htlc to fail the channel.
3406                 let update_add_htlc = msgs::UpdateAddHTLC {
3407                         channel_id: chan.2,
3408                         htlc_id: 0,
3409                         amount_msat: 0,
3410                         payment_hash,
3411                         cltv_expiry,
3412                         onion_routing_packet,
3413                 };
3414                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3415         }
3416         let events = nodes[0].node.get_and_clear_pending_events();
3417         assert_eq!(events.len(), 3);
3418         // Check that Alice fails backward the pending HTLC from the second payment.
3419         match events[0] {
3420                 Event::PaymentPathFailed { payment_hash, .. } => {
3421                         assert_eq!(payment_hash, failed_payment_hash);
3422                 },
3423                 _ => panic!("Unexpected event"),
3424         }
3425         match events[1] {
3426                 Event::PaymentFailed { payment_hash, .. } => {
3427                         assert_eq!(payment_hash, failed_payment_hash);
3428                 },
3429                 _ => panic!("Unexpected event"),
3430         }
3431         match events[2] {
3432                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3433                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3434                 },
3435                 _ => panic!("Unexpected event {:?}", events[1]),
3436         }
3437         check_closed_broadcast!(nodes[0], true);
3438         check_added_monitors!(nodes[0], 1);
3439 }
3440
3441 #[test]
3442 fn test_htlc_ignore_latest_remote_commitment() {
3443         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3444         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3445         let chanmon_cfgs = create_chanmon_cfgs(2);
3446         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3447         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3448         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3449         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3450                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3451                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3452                 // connect_style.
3453                 return;
3454         }
3455         create_announced_chan_between_nodes(&nodes, 0, 1);
3456
3457         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3458         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3459         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3460         check_closed_broadcast!(nodes[0], true);
3461         check_added_monitors!(nodes[0], 1);
3462         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3463
3464         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3465         assert_eq!(node_txn.len(), 3);
3466         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3467
3468         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3469         connect_block(&nodes[1], &block);
3470         check_closed_broadcast!(nodes[1], true);
3471         check_added_monitors!(nodes[1], 1);
3472         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3473
3474         // Duplicate the connect_block call since this may happen due to other listeners
3475         // registering new transactions
3476         connect_block(&nodes[1], &block);
3477 }
3478
3479 #[test]
3480 fn test_force_close_fail_back() {
3481         // Check which HTLCs are failed-backwards on channel force-closure
3482         let chanmon_cfgs = create_chanmon_cfgs(3);
3483         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3484         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3485         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3486         create_announced_chan_between_nodes(&nodes, 0, 1);
3487         create_announced_chan_between_nodes(&nodes, 1, 2);
3488
3489         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3490
3491         let mut payment_event = {
3492                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3493                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3494                 check_added_monitors!(nodes[0], 1);
3495
3496                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3497                 assert_eq!(events.len(), 1);
3498                 SendEvent::from_event(events.remove(0))
3499         };
3500
3501         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3502         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3503
3504         expect_pending_htlcs_forwardable!(nodes[1]);
3505
3506         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3507         assert_eq!(events_2.len(), 1);
3508         payment_event = SendEvent::from_event(events_2.remove(0));
3509         assert_eq!(payment_event.msgs.len(), 1);
3510
3511         check_added_monitors!(nodes[1], 1);
3512         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3513         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3514         check_added_monitors!(nodes[2], 1);
3515         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3516
3517         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3518         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3519         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3520
3521         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3522         check_closed_broadcast!(nodes[2], true);
3523         check_added_monitors!(nodes[2], 1);
3524         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3525         let tx = {
3526                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3527                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3528                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3529                 // back to nodes[1] upon timeout otherwise.
3530                 assert_eq!(node_txn.len(), 1);
3531                 node_txn.remove(0)
3532         };
3533
3534         mine_transaction(&nodes[1], &tx);
3535
3536         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3537         check_closed_broadcast!(nodes[1], true);
3538         check_added_monitors!(nodes[1], 1);
3539         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3540
3541         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3542         {
3543                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3544                         .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);
3545         }
3546         mine_transaction(&nodes[2], &tx);
3547         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3548         assert_eq!(node_txn.len(), 1);
3549         assert_eq!(node_txn[0].input.len(), 1);
3550         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3551         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3552         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3553
3554         check_spends!(node_txn[0], tx);
3555 }
3556
3557 #[test]
3558 fn test_dup_events_on_peer_disconnect() {
3559         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3560         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3561         // as we used to generate the event immediately upon receipt of the payment preimage in the
3562         // update_fulfill_htlc message.
3563
3564         let chanmon_cfgs = create_chanmon_cfgs(2);
3565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3568         create_announced_chan_between_nodes(&nodes, 0, 1);
3569
3570         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3571
3572         nodes[1].node.claim_funds(payment_preimage);
3573         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3574         check_added_monitors!(nodes[1], 1);
3575         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3576         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3577         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3578
3579         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3580         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3581
3582         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3583         expect_payment_path_successful!(nodes[0]);
3584 }
3585
3586 #[test]
3587 fn test_peer_disconnected_before_funding_broadcasted() {
3588         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3589         // before the funding transaction has been broadcasted.
3590         let chanmon_cfgs = create_chanmon_cfgs(2);
3591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3593         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3594
3595         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3596         // broadcasted, even though it's created by `nodes[0]`.
3597         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();
3598         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3599         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3600         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3601         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3602
3603         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3604         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3605
3606         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3607
3608         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3609         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3610
3611         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3612         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3613         // broadcasted.
3614         {
3615                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3616         }
3617
3618         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3619         // disconnected before the funding transaction was broadcasted.
3620         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3621         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3622
3623         check_closed_event(&nodes[0], 1, ClosureReason::DisconnectedPeer, false);
3624         check_closed_event(&nodes[1], 1, ClosureReason::DisconnectedPeer, false);
3625 }
3626
3627 #[test]
3628 fn test_simple_peer_disconnect() {
3629         // Test that we can reconnect when there are no lost messages
3630         let chanmon_cfgs = create_chanmon_cfgs(3);
3631         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3632         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3633         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3634         create_announced_chan_between_nodes(&nodes, 0, 1);
3635         create_announced_chan_between_nodes(&nodes, 1, 2);
3636
3637         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3638         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3639         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3640
3641         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3642         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3643         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3644         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3645
3646         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3647         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3648         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3649
3650         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3651         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3652         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3653         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3654
3655         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3656         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3657
3658         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3659         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3660
3661         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3662         {
3663                 let events = nodes[0].node.get_and_clear_pending_events();
3664                 assert_eq!(events.len(), 4);
3665                 match events[0] {
3666                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3667                                 assert_eq!(payment_preimage, payment_preimage_3);
3668                                 assert_eq!(payment_hash, payment_hash_3);
3669                         },
3670                         _ => panic!("Unexpected event"),
3671                 }
3672                 match events[1] {
3673                         Event::PaymentPathSuccessful { .. } => {},
3674                         _ => panic!("Unexpected event"),
3675                 }
3676                 match events[2] {
3677                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3678                                 assert_eq!(payment_hash, payment_hash_5);
3679                                 assert!(payment_failed_permanently);
3680                         },
3681                         _ => panic!("Unexpected event"),
3682                 }
3683                 match events[3] {
3684                         Event::PaymentFailed { payment_hash, .. } => {
3685                                 assert_eq!(payment_hash, payment_hash_5);
3686                         },
3687                         _ => panic!("Unexpected event"),
3688                 }
3689         }
3690
3691         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3692         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3693 }
3694
3695 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3696         // Test that we can reconnect when in-flight HTLC updates get dropped
3697         let chanmon_cfgs = create_chanmon_cfgs(2);
3698         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3699         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3700         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3701
3702         let mut as_channel_ready = None;
3703         let channel_id = if messages_delivered == 0 {
3704                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3705                 as_channel_ready = Some(channel_ready);
3706                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3707                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3708                 // it before the channel_reestablish message.
3709                 chan_id
3710         } else {
3711                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3712         };
3713
3714         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3715
3716         let payment_event = {
3717                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3718                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3719                 check_added_monitors!(nodes[0], 1);
3720
3721                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3722                 assert_eq!(events.len(), 1);
3723                 SendEvent::from_event(events.remove(0))
3724         };
3725         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3726
3727         if messages_delivered < 2 {
3728                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3729         } else {
3730                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3731                 if messages_delivered >= 3 {
3732                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3733                         check_added_monitors!(nodes[1], 1);
3734                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3735
3736                         if messages_delivered >= 4 {
3737                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3738                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3739                                 check_added_monitors!(nodes[0], 1);
3740
3741                                 if messages_delivered >= 5 {
3742                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3743                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3744                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3745                                         check_added_monitors!(nodes[0], 1);
3746
3747                                         if messages_delivered >= 6 {
3748                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3749                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3750                                                 check_added_monitors!(nodes[1], 1);
3751                                         }
3752                                 }
3753                         }
3754                 }
3755         }
3756
3757         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3758         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3759         if messages_delivered < 3 {
3760                 if simulate_broken_lnd {
3761                         // lnd has a long-standing bug where they send a channel_ready prior to a
3762                         // channel_reestablish if you reconnect prior to channel_ready time.
3763                         //
3764                         // Here we simulate that behavior, delivering a channel_ready immediately on
3765                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3766                         // in `reconnect_nodes` but we currently don't fail based on that.
3767                         //
3768                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3769                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3770                 }
3771                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3772                 // received on either side, both sides will need to resend them.
3773                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3774         } else if messages_delivered == 3 {
3775                 // nodes[0] still wants its RAA + commitment_signed
3776                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3777         } else if messages_delivered == 4 {
3778                 // nodes[0] still wants its commitment_signed
3779                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3780         } else if messages_delivered == 5 {
3781                 // nodes[1] still wants its final RAA
3782                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3783         } else if messages_delivered == 6 {
3784                 // Everything was delivered...
3785                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3786         }
3787
3788         let events_1 = nodes[1].node.get_and_clear_pending_events();
3789         if messages_delivered == 0 {
3790                 assert_eq!(events_1.len(), 2);
3791                 match events_1[0] {
3792                         Event::ChannelReady { .. } => { },
3793                         _ => panic!("Unexpected event"),
3794                 };
3795                 match events_1[1] {
3796                         Event::PendingHTLCsForwardable { .. } => { },
3797                         _ => panic!("Unexpected event"),
3798                 };
3799         } else {
3800                 assert_eq!(events_1.len(), 1);
3801                 match events_1[0] {
3802                         Event::PendingHTLCsForwardable { .. } => { },
3803                         _ => panic!("Unexpected event"),
3804                 };
3805         }
3806
3807         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3808         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3809         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3810
3811         nodes[1].node.process_pending_htlc_forwards();
3812
3813         let events_2 = nodes[1].node.get_and_clear_pending_events();
3814         assert_eq!(events_2.len(), 1);
3815         match events_2[0] {
3816                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3817                         assert_eq!(payment_hash_1, *payment_hash);
3818                         assert_eq!(amount_msat, 1_000_000);
3819                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3820                         assert_eq!(via_channel_id, Some(channel_id));
3821                         match &purpose {
3822                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3823                                         assert!(payment_preimage.is_none());
3824                                         assert_eq!(payment_secret_1, *payment_secret);
3825                                 },
3826                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3827                         }
3828                 },
3829                 _ => panic!("Unexpected event"),
3830         }
3831
3832         nodes[1].node.claim_funds(payment_preimage_1);
3833         check_added_monitors!(nodes[1], 1);
3834         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3835
3836         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3837         assert_eq!(events_3.len(), 1);
3838         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3839                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3840                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3841                         assert!(updates.update_add_htlcs.is_empty());
3842                         assert!(updates.update_fail_htlcs.is_empty());
3843                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3844                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3845                         assert!(updates.update_fee.is_none());
3846                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3847                 },
3848                 _ => panic!("Unexpected event"),
3849         };
3850
3851         if messages_delivered >= 1 {
3852                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3853
3854                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3855                 assert_eq!(events_4.len(), 1);
3856                 match events_4[0] {
3857                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3858                                 assert_eq!(payment_preimage_1, *payment_preimage);
3859                                 assert_eq!(payment_hash_1, *payment_hash);
3860                         },
3861                         _ => panic!("Unexpected event"),
3862                 }
3863
3864                 if messages_delivered >= 2 {
3865                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3866                         check_added_monitors!(nodes[0], 1);
3867                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3868
3869                         if messages_delivered >= 3 {
3870                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3871                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3872                                 check_added_monitors!(nodes[1], 1);
3873
3874                                 if messages_delivered >= 4 {
3875                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3876                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3877                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3878                                         check_added_monitors!(nodes[1], 1);
3879
3880                                         if messages_delivered >= 5 {
3881                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3882                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3883                                                 check_added_monitors!(nodes[0], 1);
3884                                         }
3885                                 }
3886                         }
3887                 }
3888         }
3889
3890         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3891         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3892         if messages_delivered < 2 {
3893                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3894                 if messages_delivered < 1 {
3895                         expect_payment_sent!(nodes[0], payment_preimage_1);
3896                 } else {
3897                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3898                 }
3899         } else if messages_delivered == 2 {
3900                 // nodes[0] still wants its RAA + commitment_signed
3901                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3902         } else if messages_delivered == 3 {
3903                 // nodes[0] still wants its commitment_signed
3904                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3905         } else if messages_delivered == 4 {
3906                 // nodes[1] still wants its final RAA
3907                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3908         } else if messages_delivered == 5 {
3909                 // Everything was delivered...
3910                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3911         }
3912
3913         if messages_delivered == 1 || messages_delivered == 2 {
3914                 expect_payment_path_successful!(nodes[0]);
3915         }
3916         if messages_delivered <= 5 {
3917                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3918                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3919         }
3920         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3921
3922         if messages_delivered > 2 {
3923                 expect_payment_path_successful!(nodes[0]);
3924         }
3925
3926         // Channel should still work fine...
3927         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3928         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3929         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3930 }
3931
3932 #[test]
3933 fn test_drop_messages_peer_disconnect_a() {
3934         do_test_drop_messages_peer_disconnect(0, true);
3935         do_test_drop_messages_peer_disconnect(0, false);
3936         do_test_drop_messages_peer_disconnect(1, false);
3937         do_test_drop_messages_peer_disconnect(2, false);
3938 }
3939
3940 #[test]
3941 fn test_drop_messages_peer_disconnect_b() {
3942         do_test_drop_messages_peer_disconnect(3, false);
3943         do_test_drop_messages_peer_disconnect(4, false);
3944         do_test_drop_messages_peer_disconnect(5, false);
3945         do_test_drop_messages_peer_disconnect(6, false);
3946 }
3947
3948 #[test]
3949 fn test_channel_ready_without_best_block_updated() {
3950         // Previously, if we were offline when a funding transaction was locked in, and then we came
3951         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3952         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3953         // channel_ready immediately instead.
3954         let chanmon_cfgs = create_chanmon_cfgs(2);
3955         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3956         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3957         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3958         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3959
3960         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3961
3962         let conf_height = nodes[0].best_block_info().1 + 1;
3963         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3964         let block_txn = [funding_tx];
3965         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3966         let conf_block_header = nodes[0].get_block_header(conf_height);
3967         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3968
3969         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3970         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3971         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3972 }
3973
3974 #[test]
3975 fn test_drop_messages_peer_disconnect_dual_htlc() {
3976         // Test that we can handle reconnecting when both sides of a channel have pending
3977         // commitment_updates when we disconnect.
3978         let chanmon_cfgs = create_chanmon_cfgs(2);
3979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3981         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3982         create_announced_chan_between_nodes(&nodes, 0, 1);
3983
3984         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3985
3986         // Now try to send a second payment which will fail to send
3987         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3988         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3989                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3990         check_added_monitors!(nodes[0], 1);
3991
3992         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3993         assert_eq!(events_1.len(), 1);
3994         match events_1[0] {
3995                 MessageSendEvent::UpdateHTLCs { .. } => {},
3996                 _ => panic!("Unexpected event"),
3997         }
3998
3999         nodes[1].node.claim_funds(payment_preimage_1);
4000         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4001         check_added_monitors!(nodes[1], 1);
4002
4003         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4004         assert_eq!(events_2.len(), 1);
4005         match events_2[0] {
4006                 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 } } => {
4007                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4008                         assert!(update_add_htlcs.is_empty());
4009                         assert_eq!(update_fulfill_htlcs.len(), 1);
4010                         assert!(update_fail_htlcs.is_empty());
4011                         assert!(update_fail_malformed_htlcs.is_empty());
4012                         assert!(update_fee.is_none());
4013
4014                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4015                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4016                         assert_eq!(events_3.len(), 1);
4017                         match events_3[0] {
4018                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4019                                         assert_eq!(*payment_preimage, payment_preimage_1);
4020                                         assert_eq!(*payment_hash, payment_hash_1);
4021                                 },
4022                                 _ => panic!("Unexpected event"),
4023                         }
4024
4025                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4026                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4027                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4028                         check_added_monitors!(nodes[0], 1);
4029                 },
4030                 _ => panic!("Unexpected event"),
4031         }
4032
4033         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4034         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4035
4036         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4037                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4038         }, true).unwrap();
4039         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4040         assert_eq!(reestablish_1.len(), 1);
4041         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4042                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4043         }, false).unwrap();
4044         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4045         assert_eq!(reestablish_2.len(), 1);
4046
4047         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4048         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4049         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4050         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4051
4052         assert!(as_resp.0.is_none());
4053         assert!(bs_resp.0.is_none());
4054
4055         assert!(bs_resp.1.is_none());
4056         assert!(bs_resp.2.is_none());
4057
4058         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4059
4060         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4061         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4062         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4063         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4064         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4065         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4066         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4067         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4068         // No commitment_signed so get_event_msg's assert(len == 1) passes
4069         check_added_monitors!(nodes[1], 1);
4070
4071         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4072         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4073         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4074         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4075         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4076         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4077         assert!(bs_second_commitment_signed.update_fee.is_none());
4078         check_added_monitors!(nodes[1], 1);
4079
4080         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4081         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4082         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4083         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4084         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4085         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4086         assert!(as_commitment_signed.update_fee.is_none());
4087         check_added_monitors!(nodes[0], 1);
4088
4089         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4090         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4091         // No commitment_signed so get_event_msg's assert(len == 1) passes
4092         check_added_monitors!(nodes[0], 1);
4093
4094         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4095         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4096         // No commitment_signed so get_event_msg's assert(len == 1) passes
4097         check_added_monitors!(nodes[1], 1);
4098
4099         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4100         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4101         check_added_monitors!(nodes[1], 1);
4102
4103         expect_pending_htlcs_forwardable!(nodes[1]);
4104
4105         let events_5 = nodes[1].node.get_and_clear_pending_events();
4106         assert_eq!(events_5.len(), 1);
4107         match events_5[0] {
4108                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4109                         assert_eq!(payment_hash_2, *payment_hash);
4110                         match &purpose {
4111                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4112                                         assert!(payment_preimage.is_none());
4113                                         assert_eq!(payment_secret_2, *payment_secret);
4114                                 },
4115                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4116                         }
4117                 },
4118                 _ => panic!("Unexpected event"),
4119         }
4120
4121         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4122         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4123         check_added_monitors!(nodes[0], 1);
4124
4125         expect_payment_path_successful!(nodes[0]);
4126         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4127 }
4128
4129 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4130         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4131         // to avoid our counterparty failing the channel.
4132         let chanmon_cfgs = create_chanmon_cfgs(2);
4133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4136
4137         create_announced_chan_between_nodes(&nodes, 0, 1);
4138
4139         let our_payment_hash = if send_partial_mpp {
4140                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4141                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4142                 // indicates there are more HTLCs coming.
4143                 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.
4144                 let payment_id = PaymentId([42; 32]);
4145                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4146                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4147                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4148                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4149                         &None, session_privs[0]).unwrap();
4150                 check_added_monitors!(nodes[0], 1);
4151                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4152                 assert_eq!(events.len(), 1);
4153                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4154                 // hop should *not* yet generate any PaymentClaimable event(s).
4155                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4156                 our_payment_hash
4157         } else {
4158                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4159         };
4160
4161         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4162         connect_block(&nodes[0], &block);
4163         connect_block(&nodes[1], &block);
4164         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4165         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4166                 block.header.prev_blockhash = block.block_hash();
4167                 connect_block(&nodes[0], &block);
4168                 connect_block(&nodes[1], &block);
4169         }
4170
4171         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4172
4173         check_added_monitors!(nodes[1], 1);
4174         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4175         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4176         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4177         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4178         assert!(htlc_timeout_updates.update_fee.is_none());
4179
4180         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4181         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4182         // 100_000 msat as u64, followed by the height at which we failed back above
4183         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4184         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4185         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4186 }
4187
4188 #[test]
4189 fn test_htlc_timeout() {
4190         do_test_htlc_timeout(true);
4191         do_test_htlc_timeout(false);
4192 }
4193
4194 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4195         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4196         let chanmon_cfgs = create_chanmon_cfgs(3);
4197         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4198         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4199         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4200         create_announced_chan_between_nodes(&nodes, 0, 1);
4201         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4202
4203         // Make sure all nodes are at the same starting height
4204         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4205         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4206         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4207
4208         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4209         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4210         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4211                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4212         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4213         check_added_monitors!(nodes[1], 1);
4214
4215         // Now attempt to route a second payment, which should be placed in the holding cell
4216         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4217         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4218         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4219                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4220         if forwarded_htlc {
4221                 check_added_monitors!(nodes[0], 1);
4222                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4223                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4224                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4225                 expect_pending_htlcs_forwardable!(nodes[1]);
4226         }
4227         check_added_monitors!(nodes[1], 0);
4228
4229         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4230         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4231         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4232         connect_blocks(&nodes[1], 1);
4233
4234         if forwarded_htlc {
4235                 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 }]);
4236                 check_added_monitors!(nodes[1], 1);
4237                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4238                 assert_eq!(fail_commit.len(), 1);
4239                 match fail_commit[0] {
4240                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4241                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4242                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4243                         },
4244                         _ => unreachable!(),
4245                 }
4246                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4247         } else {
4248                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4249         }
4250 }
4251
4252 #[test]
4253 fn test_holding_cell_htlc_add_timeouts() {
4254         do_test_holding_cell_htlc_add_timeouts(false);
4255         do_test_holding_cell_htlc_add_timeouts(true);
4256 }
4257
4258 macro_rules! check_spendable_outputs {
4259         ($node: expr, $keysinterface: expr) => {
4260                 {
4261                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4262                         let mut txn = Vec::new();
4263                         let mut all_outputs = Vec::new();
4264                         let secp_ctx = Secp256k1::new();
4265                         for event in events.drain(..) {
4266                                 match event {
4267                                         Event::SpendableOutputs { mut outputs } => {
4268                                                 for outp in outputs.drain(..) {
4269                                                         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());
4270                                                         all_outputs.push(outp);
4271                                                 }
4272                                         },
4273                                         _ => panic!("Unexpected event"),
4274                                 };
4275                         }
4276                         if all_outputs.len() > 1 {
4277                                 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) {
4278                                         txn.push(tx);
4279                                 }
4280                         }
4281                         txn
4282                 }
4283         }
4284 }
4285
4286 #[test]
4287 fn test_claim_sizeable_push_msat() {
4288         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4289         let chanmon_cfgs = create_chanmon_cfgs(2);
4290         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4291         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4292         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4293
4294         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4295         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4296         check_closed_broadcast!(nodes[1], true);
4297         check_added_monitors!(nodes[1], 1);
4298         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4299         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4300         assert_eq!(node_txn.len(), 1);
4301         check_spends!(node_txn[0], chan.3);
4302         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
4303
4304         mine_transaction(&nodes[1], &node_txn[0]);
4305         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4306
4307         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4308         assert_eq!(spend_txn.len(), 1);
4309         assert_eq!(spend_txn[0].input.len(), 1);
4310         check_spends!(spend_txn[0], node_txn[0]);
4311         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4312 }
4313
4314 #[test]
4315 fn test_claim_on_remote_sizeable_push_msat() {
4316         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4317         // to_remote output is encumbered by a P2WPKH
4318         let chanmon_cfgs = create_chanmon_cfgs(2);
4319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4321         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4322
4323         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4324         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4325         check_closed_broadcast!(nodes[0], true);
4326         check_added_monitors!(nodes[0], 1);
4327         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4328
4329         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4330         assert_eq!(node_txn.len(), 1);
4331         check_spends!(node_txn[0], chan.3);
4332         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
4333
4334         mine_transaction(&nodes[1], &node_txn[0]);
4335         check_closed_broadcast!(nodes[1], true);
4336         check_added_monitors!(nodes[1], 1);
4337         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4338         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4339
4340         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4341         assert_eq!(spend_txn.len(), 1);
4342         check_spends!(spend_txn[0], node_txn[0]);
4343 }
4344
4345 #[test]
4346 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4347         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4348         // to_remote output is encumbered by a P2WPKH
4349
4350         let chanmon_cfgs = create_chanmon_cfgs(2);
4351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4352         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4353         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4354
4355         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4356         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4357         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4358         assert_eq!(revoked_local_txn[0].input.len(), 1);
4359         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4360
4361         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4362         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4363         check_closed_broadcast!(nodes[1], true);
4364         check_added_monitors!(nodes[1], 1);
4365         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4366
4367         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4368         mine_transaction(&nodes[1], &node_txn[0]);
4369         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4370
4371         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4372         assert_eq!(spend_txn.len(), 3);
4373         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4374         check_spends!(spend_txn[1], node_txn[0]);
4375         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4376 }
4377
4378 #[test]
4379 fn test_static_spendable_outputs_preimage_tx() {
4380         let chanmon_cfgs = create_chanmon_cfgs(2);
4381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4383         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4384
4385         // Create some initial channels
4386         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4387
4388         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4389
4390         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4391         assert_eq!(commitment_tx[0].input.len(), 1);
4392         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4393
4394         // Settle A's commitment tx on B's chain
4395         nodes[1].node.claim_funds(payment_preimage);
4396         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4397         check_added_monitors!(nodes[1], 1);
4398         mine_transaction(&nodes[1], &commitment_tx[0]);
4399         check_added_monitors!(nodes[1], 1);
4400         let events = nodes[1].node.get_and_clear_pending_msg_events();
4401         match events[0] {
4402                 MessageSendEvent::UpdateHTLCs { .. } => {},
4403                 _ => panic!("Unexpected event"),
4404         }
4405         match events[1] {
4406                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4407                 _ => panic!("Unexepected event"),
4408         }
4409
4410         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4411         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4412         assert_eq!(node_txn.len(), 1);
4413         check_spends!(node_txn[0], commitment_tx[0]);
4414         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4415
4416         mine_transaction(&nodes[1], &node_txn[0]);
4417         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4418         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4419
4420         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4421         assert_eq!(spend_txn.len(), 1);
4422         check_spends!(spend_txn[0], node_txn[0]);
4423 }
4424
4425 #[test]
4426 fn test_static_spendable_outputs_timeout_tx() {
4427         let chanmon_cfgs = create_chanmon_cfgs(2);
4428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4430         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4431
4432         // Create some initial channels
4433         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4434
4435         // Rebalance the network a bit by relaying one payment through all the channels ...
4436         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4437
4438         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4439
4440         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4441         assert_eq!(commitment_tx[0].input.len(), 1);
4442         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4443
4444         // Settle A's commitment tx on B' chain
4445         mine_transaction(&nodes[1], &commitment_tx[0]);
4446         check_added_monitors!(nodes[1], 1);
4447         let events = nodes[1].node.get_and_clear_pending_msg_events();
4448         match events[0] {
4449                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4450                 _ => panic!("Unexpected event"),
4451         }
4452         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4453
4454         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4455         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4456         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4457         check_spends!(node_txn[0],  commitment_tx[0].clone());
4458         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4459
4460         mine_transaction(&nodes[1], &node_txn[0]);
4461         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4462         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4463         expect_payment_failed!(nodes[1], our_payment_hash, false);
4464
4465         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4466         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4467         check_spends!(spend_txn[0], commitment_tx[0]);
4468         check_spends!(spend_txn[1], node_txn[0]);
4469         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4470 }
4471
4472 #[test]
4473 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4474         let chanmon_cfgs = create_chanmon_cfgs(2);
4475         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4476         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4477         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4478
4479         // Create some initial channels
4480         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4481
4482         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4483         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4484         assert_eq!(revoked_local_txn[0].input.len(), 1);
4485         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4486
4487         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4488
4489         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4490         check_closed_broadcast!(nodes[1], true);
4491         check_added_monitors!(nodes[1], 1);
4492         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4493
4494         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4495         assert_eq!(node_txn.len(), 1);
4496         assert_eq!(node_txn[0].input.len(), 2);
4497         check_spends!(node_txn[0], revoked_local_txn[0]);
4498
4499         mine_transaction(&nodes[1], &node_txn[0]);
4500         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4501
4502         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4503         assert_eq!(spend_txn.len(), 1);
4504         check_spends!(spend_txn[0], node_txn[0]);
4505 }
4506
4507 #[test]
4508 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4509         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4510         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4511         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4512         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4513         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4514
4515         // Create some initial channels
4516         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4517
4518         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4519         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4520         assert_eq!(revoked_local_txn[0].input.len(), 1);
4521         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4522
4523         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4524
4525         // A will generate HTLC-Timeout from revoked commitment tx
4526         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4527         check_closed_broadcast!(nodes[0], true);
4528         check_added_monitors!(nodes[0], 1);
4529         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4530         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4531
4532         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4533         assert_eq!(revoked_htlc_txn.len(), 1);
4534         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4535         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4536         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4537         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4538
4539         // B will generate justice tx from A's revoked commitment/HTLC tx
4540         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4541         check_closed_broadcast!(nodes[1], true);
4542         check_added_monitors!(nodes[1], 1);
4543         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4544
4545         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4546         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4547         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4548         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4549         // transactions next...
4550         assert_eq!(node_txn[0].input.len(), 3);
4551         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4552
4553         assert_eq!(node_txn[1].input.len(), 2);
4554         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4555         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4556                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4557         } else {
4558                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4559                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4560         }
4561
4562         mine_transaction(&nodes[1], &node_txn[1]);
4563         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4564
4565         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4566         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4567         assert_eq!(spend_txn.len(), 1);
4568         assert_eq!(spend_txn[0].input.len(), 1);
4569         check_spends!(spend_txn[0], node_txn[1]);
4570 }
4571
4572 #[test]
4573 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4574         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4575         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4579
4580         // Create some initial channels
4581         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4582
4583         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4584         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4585         assert_eq!(revoked_local_txn[0].input.len(), 1);
4586         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4587
4588         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4589         assert_eq!(revoked_local_txn[0].output.len(), 2);
4590
4591         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4592
4593         // B will generate HTLC-Success from revoked commitment tx
4594         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4595         check_closed_broadcast!(nodes[1], true);
4596         check_added_monitors!(nodes[1], 1);
4597         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4598         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4599
4600         assert_eq!(revoked_htlc_txn.len(), 1);
4601         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4602         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4603         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4604
4605         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4606         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4607         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4608
4609         // A will generate justice tx from B's revoked commitment/HTLC tx
4610         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4611         check_closed_broadcast!(nodes[0], true);
4612         check_added_monitors!(nodes[0], 1);
4613         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4614
4615         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4616         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4617
4618         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4619         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4620         // transactions next...
4621         assert_eq!(node_txn[0].input.len(), 2);
4622         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4623         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4624                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4625         } else {
4626                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4627                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4628         }
4629
4630         assert_eq!(node_txn[1].input.len(), 1);
4631         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4632
4633         mine_transaction(&nodes[0], &node_txn[1]);
4634         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4635
4636         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4637         // didn't try to generate any new transactions.
4638
4639         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4640         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4641         assert_eq!(spend_txn.len(), 3);
4642         assert_eq!(spend_txn[0].input.len(), 1);
4643         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4644         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4645         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4646         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4647 }
4648
4649 #[test]
4650 fn test_onchain_to_onchain_claim() {
4651         // Test that in case of channel closure, we detect the state of output and claim HTLC
4652         // on downstream peer's remote commitment tx.
4653         // First, have C claim an HTLC against its own latest commitment transaction.
4654         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4655         // channel.
4656         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4657         // gets broadcast.
4658
4659         let chanmon_cfgs = create_chanmon_cfgs(3);
4660         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4661         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4662         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4663
4664         // Create some initial channels
4665         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4666         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4667
4668         // Ensure all nodes are at the same height
4669         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4670         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4671         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4672         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4673
4674         // Rebalance the network a bit by relaying one payment through all the channels ...
4675         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4676         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4677
4678         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4679         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4680         check_spends!(commitment_tx[0], chan_2.3);
4681         nodes[2].node.claim_funds(payment_preimage);
4682         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4683         check_added_monitors!(nodes[2], 1);
4684         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4685         assert!(updates.update_add_htlcs.is_empty());
4686         assert!(updates.update_fail_htlcs.is_empty());
4687         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4688         assert!(updates.update_fail_malformed_htlcs.is_empty());
4689
4690         mine_transaction(&nodes[2], &commitment_tx[0]);
4691         check_closed_broadcast!(nodes[2], true);
4692         check_added_monitors!(nodes[2], 1);
4693         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4694
4695         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4696         assert_eq!(c_txn.len(), 1);
4697         check_spends!(c_txn[0], commitment_tx[0]);
4698         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4699         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4700         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4701
4702         // 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
4703         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4704         check_added_monitors!(nodes[1], 1);
4705         let events = nodes[1].node.get_and_clear_pending_events();
4706         assert_eq!(events.len(), 2);
4707         match events[0] {
4708                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4709                 _ => panic!("Unexpected event"),
4710         }
4711         match events[1] {
4712                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4713                         assert_eq!(fee_earned_msat, Some(1000));
4714                         assert_eq!(prev_channel_id, Some(chan_1.2));
4715                         assert_eq!(claim_from_onchain_tx, true);
4716                         assert_eq!(next_channel_id, Some(chan_2.2));
4717                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4718                 },
4719                 _ => panic!("Unexpected event"),
4720         }
4721         check_added_monitors!(nodes[1], 1);
4722         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4723         assert_eq!(msg_events.len(), 3);
4724         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4725         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4726
4727         match nodes_2_event {
4728                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4729                 _ => panic!("Unexpected event"),
4730         }
4731
4732         match nodes_0_event {
4733                 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, .. } } => {
4734                         assert!(update_add_htlcs.is_empty());
4735                         assert!(update_fail_htlcs.is_empty());
4736                         assert_eq!(update_fulfill_htlcs.len(), 1);
4737                         assert!(update_fail_malformed_htlcs.is_empty());
4738                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4739                 },
4740                 _ => panic!("Unexpected event"),
4741         };
4742
4743         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4744         match msg_events[0] {
4745                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4746                 _ => panic!("Unexpected event"),
4747         }
4748
4749         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4750         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4751         mine_transaction(&nodes[1], &commitment_tx[0]);
4752         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4753         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4754         // ChannelMonitor: HTLC-Success tx
4755         assert_eq!(b_txn.len(), 1);
4756         check_spends!(b_txn[0], commitment_tx[0]);
4757         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4758         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4759         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4760
4761         check_closed_broadcast!(nodes[1], true);
4762         check_added_monitors!(nodes[1], 1);
4763 }
4764
4765 #[test]
4766 fn test_duplicate_payment_hash_one_failure_one_success() {
4767         // Topology : A --> B --> C --> D
4768         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4769         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4770         // we forward one of the payments onwards to D.
4771         let chanmon_cfgs = create_chanmon_cfgs(4);
4772         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4773         // When this test was written, the default base fee floated based on the HTLC count.
4774         // It is now fixed, so we simply set the fee to the expected value here.
4775         let mut config = test_default_channel_config();
4776         config.channel_config.forwarding_fee_base_msat = 196;
4777         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4778                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4779         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4780
4781         create_announced_chan_between_nodes(&nodes, 0, 1);
4782         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4783         create_announced_chan_between_nodes(&nodes, 2, 3);
4784
4785         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4786         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4787         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4788         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4789         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4790
4791         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4792
4793         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4794         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4795         // script push size limit so that the below script length checks match
4796         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4797         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4798                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4799         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4800         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4801
4802         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4803         assert_eq!(commitment_txn[0].input.len(), 1);
4804         check_spends!(commitment_txn[0], chan_2.3);
4805
4806         mine_transaction(&nodes[1], &commitment_txn[0]);
4807         check_closed_broadcast!(nodes[1], true);
4808         check_added_monitors!(nodes[1], 1);
4809         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4810         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4811
4812         let htlc_timeout_tx;
4813         { // Extract one of the two HTLC-Timeout transaction
4814                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4815                 // ChannelMonitor: timeout tx * 2-or-3
4816                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4817
4818                 check_spends!(node_txn[0], commitment_txn[0]);
4819                 assert_eq!(node_txn[0].input.len(), 1);
4820                 assert_eq!(node_txn[0].output.len(), 1);
4821
4822                 if node_txn.len() > 2 {
4823                         check_spends!(node_txn[1], commitment_txn[0]);
4824                         assert_eq!(node_txn[1].input.len(), 1);
4825                         assert_eq!(node_txn[1].output.len(), 1);
4826                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4827
4828                         check_spends!(node_txn[2], commitment_txn[0]);
4829                         assert_eq!(node_txn[2].input.len(), 1);
4830                         assert_eq!(node_txn[2].output.len(), 1);
4831                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4832                 } else {
4833                         check_spends!(node_txn[1], commitment_txn[0]);
4834                         assert_eq!(node_txn[1].input.len(), 1);
4835                         assert_eq!(node_txn[1].output.len(), 1);
4836                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4837                 }
4838
4839                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4840                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4841                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4842                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4843                 if node_txn.len() > 2 {
4844                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4845                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4846                 } else {
4847                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4848                 }
4849         }
4850
4851         nodes[2].node.claim_funds(our_payment_preimage);
4852         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4853
4854         mine_transaction(&nodes[2], &commitment_txn[0]);
4855         check_added_monitors!(nodes[2], 2);
4856         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4857         let events = nodes[2].node.get_and_clear_pending_msg_events();
4858         match events[0] {
4859                 MessageSendEvent::UpdateHTLCs { .. } => {},
4860                 _ => panic!("Unexpected event"),
4861         }
4862         match events[1] {
4863                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4864                 _ => panic!("Unexepected event"),
4865         }
4866         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4867         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4868         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4869         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4870         assert_eq!(htlc_success_txn[0].input.len(), 1);
4871         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4872         assert_eq!(htlc_success_txn[1].input.len(), 1);
4873         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4874         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4875         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4876
4877         mine_transaction(&nodes[1], &htlc_timeout_tx);
4878         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4879         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 }]);
4880         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4881         assert!(htlc_updates.update_add_htlcs.is_empty());
4882         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4883         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4884         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4885         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4886         check_added_monitors!(nodes[1], 1);
4887
4888         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4889         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4890         {
4891                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4892         }
4893         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4894
4895         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4896         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4897         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4898         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4899         assert!(updates.update_add_htlcs.is_empty());
4900         assert!(updates.update_fail_htlcs.is_empty());
4901         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4902         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4903         assert!(updates.update_fail_malformed_htlcs.is_empty());
4904         check_added_monitors!(nodes[1], 1);
4905
4906         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4907         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4908         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4909 }
4910
4911 #[test]
4912 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4913         let chanmon_cfgs = create_chanmon_cfgs(2);
4914         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4915         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4916         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4917
4918         // Create some initial channels
4919         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4920
4921         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4922         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4923         assert_eq!(local_txn.len(), 1);
4924         assert_eq!(local_txn[0].input.len(), 1);
4925         check_spends!(local_txn[0], chan_1.3);
4926
4927         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4928         nodes[1].node.claim_funds(payment_preimage);
4929         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4930         check_added_monitors!(nodes[1], 1);
4931
4932         mine_transaction(&nodes[1], &local_txn[0]);
4933         check_added_monitors!(nodes[1], 1);
4934         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4935         let events = nodes[1].node.get_and_clear_pending_msg_events();
4936         match events[0] {
4937                 MessageSendEvent::UpdateHTLCs { .. } => {},
4938                 _ => panic!("Unexpected event"),
4939         }
4940         match events[1] {
4941                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4942                 _ => panic!("Unexepected event"),
4943         }
4944         let node_tx = {
4945                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4946                 assert_eq!(node_txn.len(), 1);
4947                 assert_eq!(node_txn[0].input.len(), 1);
4948                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4949                 check_spends!(node_txn[0], local_txn[0]);
4950                 node_txn[0].clone()
4951         };
4952
4953         mine_transaction(&nodes[1], &node_tx);
4954         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4955
4956         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4957         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4958         assert_eq!(spend_txn.len(), 1);
4959         assert_eq!(spend_txn[0].input.len(), 1);
4960         check_spends!(spend_txn[0], node_tx);
4961         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4962 }
4963
4964 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4965         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4966         // unrevoked commitment transaction.
4967         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4968         // a remote RAA before they could be failed backwards (and combinations thereof).
4969         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4970         // use the same payment hashes.
4971         // Thus, we use a six-node network:
4972         //
4973         // A \         / E
4974         //    - C - D -
4975         // B /         \ F
4976         // And test where C fails back to A/B when D announces its latest commitment transaction
4977         let chanmon_cfgs = create_chanmon_cfgs(6);
4978         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4979         // When this test was written, the default base fee floated based on the HTLC count.
4980         // It is now fixed, so we simply set the fee to the expected value here.
4981         let mut config = test_default_channel_config();
4982         config.channel_config.forwarding_fee_base_msat = 196;
4983         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4984                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4985         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4986
4987         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4988         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4989         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4990         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4991         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4992
4993         // Rebalance and check output sanity...
4994         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4995         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4996         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4997
4998         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4999                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5000         // 0th HTLC:
5001         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
5002         // 1st HTLC:
5003         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
5004         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5005         // 2nd HTLC:
5006         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
5007         // 3rd HTLC:
5008         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
5009         // 4th HTLC:
5010         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5011         // 5th HTLC:
5012         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5013         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5014         // 6th HTLC:
5015         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());
5016         // 7th HTLC:
5017         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());
5018
5019         // 8th HTLC:
5020         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5021         // 9th HTLC:
5022         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5023         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
5024
5025         // 10th HTLC:
5026         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
5027         // 11th HTLC:
5028         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5029         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());
5030
5031         // Double-check that six of the new HTLC were added
5032         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5033         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5034         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5035         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5036
5037         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5038         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5039         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5040         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5041         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5042         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5043         check_added_monitors!(nodes[4], 0);
5044
5045         let failed_destinations = vec![
5046                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5047                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5048                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5049                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5050         ];
5051         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5052         check_added_monitors!(nodes[4], 1);
5053
5054         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5055         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5056         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5057         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5058         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5059         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5060
5061         // Fail 3rd below-dust and 7th above-dust HTLCs
5062         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5063         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5064         check_added_monitors!(nodes[5], 0);
5065
5066         let failed_destinations_2 = vec![
5067                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5068                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5069         ];
5070         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5071         check_added_monitors!(nodes[5], 1);
5072
5073         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5074         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5075         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5076         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5077
5078         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5079
5080         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5081         let failed_destinations_3 = vec![
5082                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5083                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5084                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5085                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5086                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5087                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5088         ];
5089         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5090         check_added_monitors!(nodes[3], 1);
5091         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5092         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5093         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5094         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5095         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5096         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5097         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5098         if deliver_last_raa {
5099                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5100         } else {
5101                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5102         }
5103
5104         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5105         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5106         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5107         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5108         //
5109         // We now broadcast the latest commitment transaction, which *should* result in failures for
5110         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5111         // the non-broadcast above-dust HTLCs.
5112         //
5113         // Alternatively, we may broadcast the previous commitment transaction, which should only
5114         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5115         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5116
5117         if announce_latest {
5118                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5119         } else {
5120                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5121         }
5122         let events = nodes[2].node.get_and_clear_pending_events();
5123         let close_event = if deliver_last_raa {
5124                 assert_eq!(events.len(), 2 + 6);
5125                 events.last().clone().unwrap()
5126         } else {
5127                 assert_eq!(events.len(), 1);
5128                 events.last().clone().unwrap()
5129         };
5130         match close_event {
5131                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5132                 _ => panic!("Unexpected event"),
5133         }
5134
5135         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5136         check_closed_broadcast!(nodes[2], true);
5137         if deliver_last_raa {
5138                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5139
5140                 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();
5141                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5142         } else {
5143                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5144                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5145                 } else {
5146                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5147                 };
5148
5149                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5150         }
5151         check_added_monitors!(nodes[2], 3);
5152
5153         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5154         assert_eq!(cs_msgs.len(), 2);
5155         let mut a_done = false;
5156         for msg in cs_msgs {
5157                 match msg {
5158                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5159                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5160                                 // should be failed-backwards here.
5161                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5162                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5163                                         for htlc in &updates.update_fail_htlcs {
5164                                                 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 });
5165                                         }
5166                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5167                                         assert!(!a_done);
5168                                         a_done = true;
5169                                         &nodes[0]
5170                                 } else {
5171                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5172                                         for htlc in &updates.update_fail_htlcs {
5173                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5174                                         }
5175                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5176                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5177                                         &nodes[1]
5178                                 };
5179                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5180                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5181                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5182                                 if announce_latest {
5183                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5184                                         if *node_id == nodes[0].node.get_our_node_id() {
5185                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5186                                         }
5187                                 }
5188                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5189                         },
5190                         _ => panic!("Unexpected event"),
5191                 }
5192         }
5193
5194         let as_events = nodes[0].node.get_and_clear_pending_events();
5195         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5196         let mut as_failds = HashSet::new();
5197         let mut as_updates = 0;
5198         for event in as_events.iter() {
5199                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5200                         assert!(as_failds.insert(*payment_hash));
5201                         if *payment_hash != payment_hash_2 {
5202                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5203                         } else {
5204                                 assert!(!payment_failed_permanently);
5205                         }
5206                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5207                                 as_updates += 1;
5208                         }
5209                 } else if let &Event::PaymentFailed { .. } = event {
5210                 } else { panic!("Unexpected event"); }
5211         }
5212         assert!(as_failds.contains(&payment_hash_1));
5213         assert!(as_failds.contains(&payment_hash_2));
5214         if announce_latest {
5215                 assert!(as_failds.contains(&payment_hash_3));
5216                 assert!(as_failds.contains(&payment_hash_5));
5217         }
5218         assert!(as_failds.contains(&payment_hash_6));
5219
5220         let bs_events = nodes[1].node.get_and_clear_pending_events();
5221         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5222         let mut bs_failds = HashSet::new();
5223         let mut bs_updates = 0;
5224         for event in bs_events.iter() {
5225                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5226                         assert!(bs_failds.insert(*payment_hash));
5227                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5228                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5229                         } else {
5230                                 assert!(!payment_failed_permanently);
5231                         }
5232                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5233                                 bs_updates += 1;
5234                         }
5235                 } else if let &Event::PaymentFailed { .. } = event {
5236                 } else { panic!("Unexpected event"); }
5237         }
5238         assert!(bs_failds.contains(&payment_hash_1));
5239         assert!(bs_failds.contains(&payment_hash_2));
5240         if announce_latest {
5241                 assert!(bs_failds.contains(&payment_hash_4));
5242         }
5243         assert!(bs_failds.contains(&payment_hash_5));
5244
5245         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5246         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5247         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5248         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5249         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5250         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5251 }
5252
5253 #[test]
5254 fn test_fail_backwards_latest_remote_announce_a() {
5255         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5256 }
5257
5258 #[test]
5259 fn test_fail_backwards_latest_remote_announce_b() {
5260         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5261 }
5262
5263 #[test]
5264 fn test_fail_backwards_previous_remote_announce() {
5265         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5266         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5267         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5268 }
5269
5270 #[test]
5271 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5272         let chanmon_cfgs = create_chanmon_cfgs(2);
5273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5276
5277         // Create some initial channels
5278         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5279
5280         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5281         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5282         assert_eq!(local_txn[0].input.len(), 1);
5283         check_spends!(local_txn[0], chan_1.3);
5284
5285         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5286         mine_transaction(&nodes[0], &local_txn[0]);
5287         check_closed_broadcast!(nodes[0], true);
5288         check_added_monitors!(nodes[0], 1);
5289         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5290         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5291
5292         let htlc_timeout = {
5293                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5294                 assert_eq!(node_txn.len(), 1);
5295                 assert_eq!(node_txn[0].input.len(), 1);
5296                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5297                 check_spends!(node_txn[0], local_txn[0]);
5298                 node_txn[0].clone()
5299         };
5300
5301         mine_transaction(&nodes[0], &htlc_timeout);
5302         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5303         expect_payment_failed!(nodes[0], our_payment_hash, false);
5304
5305         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5306         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5307         assert_eq!(spend_txn.len(), 3);
5308         check_spends!(spend_txn[0], local_txn[0]);
5309         assert_eq!(spend_txn[1].input.len(), 1);
5310         check_spends!(spend_txn[1], htlc_timeout);
5311         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5312         assert_eq!(spend_txn[2].input.len(), 2);
5313         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5314         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5315                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5316 }
5317
5318 #[test]
5319 fn test_key_derivation_params() {
5320         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5321         // manager rotation to test that `channel_keys_id` returned in
5322         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5323         // then derive a `delayed_payment_key`.
5324
5325         let chanmon_cfgs = create_chanmon_cfgs(3);
5326
5327         // We manually create the node configuration to backup the seed.
5328         let seed = [42; 32];
5329         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5330         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);
5331         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5332         let scorer = Mutex::new(test_utils::TestScorer::new());
5333         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5334         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)) };
5335         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5336         node_cfgs.remove(0);
5337         node_cfgs.insert(0, node);
5338
5339         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5340         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5341
5342         // Create some initial channels
5343         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5344         // for node 0
5345         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5346         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5347         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5348
5349         // Ensure all nodes are at the same height
5350         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5351         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5352         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5353         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5354
5355         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5356         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5357         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5358         assert_eq!(local_txn_1[0].input.len(), 1);
5359         check_spends!(local_txn_1[0], chan_1.3);
5360
5361         // We check funding pubkey are unique
5362         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]));
5363         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]));
5364         if from_0_funding_key_0 == from_1_funding_key_0
5365             || from_0_funding_key_0 == from_1_funding_key_1
5366             || from_0_funding_key_1 == from_1_funding_key_0
5367             || from_0_funding_key_1 == from_1_funding_key_1 {
5368                 panic!("Funding pubkeys aren't unique");
5369         }
5370
5371         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5372         mine_transaction(&nodes[0], &local_txn_1[0]);
5373         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5374         check_closed_broadcast!(nodes[0], true);
5375         check_added_monitors!(nodes[0], 1);
5376         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5377
5378         let htlc_timeout = {
5379                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5380                 assert_eq!(node_txn.len(), 1);
5381                 assert_eq!(node_txn[0].input.len(), 1);
5382                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5383                 check_spends!(node_txn[0], local_txn_1[0]);
5384                 node_txn[0].clone()
5385         };
5386
5387         mine_transaction(&nodes[0], &htlc_timeout);
5388         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5389         expect_payment_failed!(nodes[0], our_payment_hash, false);
5390
5391         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5392         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5393         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5394         assert_eq!(spend_txn.len(), 3);
5395         check_spends!(spend_txn[0], local_txn_1[0]);
5396         assert_eq!(spend_txn[1].input.len(), 1);
5397         check_spends!(spend_txn[1], htlc_timeout);
5398         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5399         assert_eq!(spend_txn[2].input.len(), 2);
5400         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5401         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5402                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5403 }
5404
5405 #[test]
5406 fn test_static_output_closing_tx() {
5407         let chanmon_cfgs = create_chanmon_cfgs(2);
5408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5411
5412         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5413
5414         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5415         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5416
5417         mine_transaction(&nodes[0], &closing_tx);
5418         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5419         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5420
5421         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5422         assert_eq!(spend_txn.len(), 1);
5423         check_spends!(spend_txn[0], closing_tx);
5424
5425         mine_transaction(&nodes[1], &closing_tx);
5426         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5427         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5428
5429         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5430         assert_eq!(spend_txn.len(), 1);
5431         check_spends!(spend_txn[0], closing_tx);
5432 }
5433
5434 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5435         let chanmon_cfgs = create_chanmon_cfgs(2);
5436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5439         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5440
5441         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5442
5443         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5444         // present in B's local commitment transaction, but none of A's commitment transactions.
5445         nodes[1].node.claim_funds(payment_preimage);
5446         check_added_monitors!(nodes[1], 1);
5447         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5448
5449         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5450         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5451         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5452
5453         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5454         check_added_monitors!(nodes[0], 1);
5455         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5456         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5457         check_added_monitors!(nodes[1], 1);
5458
5459         let starting_block = nodes[1].best_block_info();
5460         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5461         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5462                 connect_block(&nodes[1], &block);
5463                 block.header.prev_blockhash = block.block_hash();
5464         }
5465         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5466         check_closed_broadcast!(nodes[1], true);
5467         check_added_monitors!(nodes[1], 1);
5468         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5469 }
5470
5471 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5472         let chanmon_cfgs = create_chanmon_cfgs(2);
5473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5475         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5476         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5477
5478         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5479         nodes[0].node.send_payment_with_route(&route, payment_hash,
5480                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5481         check_added_monitors!(nodes[0], 1);
5482
5483         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5484
5485         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5486         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5487         // to "time out" the HTLC.
5488
5489         let starting_block = nodes[1].best_block_info();
5490         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5491
5492         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5493                 connect_block(&nodes[0], &block);
5494                 block.header.prev_blockhash = block.block_hash();
5495         }
5496         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5497         check_closed_broadcast!(nodes[0], true);
5498         check_added_monitors!(nodes[0], 1);
5499         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5500 }
5501
5502 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5503         let chanmon_cfgs = create_chanmon_cfgs(3);
5504         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5505         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5506         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5507         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5508
5509         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5510         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5511         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5512         // actually revoked.
5513         let htlc_value = if use_dust { 50000 } else { 3000000 };
5514         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5515         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5516         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5517         check_added_monitors!(nodes[1], 1);
5518
5519         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5520         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5521         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5522         check_added_monitors!(nodes[0], 1);
5523         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5524         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5525         check_added_monitors!(nodes[1], 1);
5526         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5527         check_added_monitors!(nodes[1], 1);
5528         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5529
5530         if check_revoke_no_close {
5531                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5532                 check_added_monitors!(nodes[0], 1);
5533         }
5534
5535         let starting_block = nodes[1].best_block_info();
5536         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5537         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5538                 connect_block(&nodes[0], &block);
5539                 block.header.prev_blockhash = block.block_hash();
5540         }
5541         if !check_revoke_no_close {
5542                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5543                 check_closed_broadcast!(nodes[0], true);
5544                 check_added_monitors!(nodes[0], 1);
5545                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5546         } else {
5547                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5548         }
5549 }
5550
5551 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5552 // There are only a few cases to test here:
5553 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5554 //    broadcastable commitment transactions result in channel closure,
5555 //  * its included in an unrevoked-but-previous remote commitment transaction,
5556 //  * its included in the latest remote or local commitment transactions.
5557 // We test each of the three possible commitment transactions individually and use both dust and
5558 // non-dust HTLCs.
5559 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5560 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5561 // tested for at least one of the cases in other tests.
5562 #[test]
5563 fn htlc_claim_single_commitment_only_a() {
5564         do_htlc_claim_local_commitment_only(true);
5565         do_htlc_claim_local_commitment_only(false);
5566
5567         do_htlc_claim_current_remote_commitment_only(true);
5568         do_htlc_claim_current_remote_commitment_only(false);
5569 }
5570
5571 #[test]
5572 fn htlc_claim_single_commitment_only_b() {
5573         do_htlc_claim_previous_remote_commitment_only(true, false);
5574         do_htlc_claim_previous_remote_commitment_only(false, false);
5575         do_htlc_claim_previous_remote_commitment_only(true, true);
5576         do_htlc_claim_previous_remote_commitment_only(false, true);
5577 }
5578
5579 #[test]
5580 #[should_panic]
5581 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5582         let chanmon_cfgs = create_chanmon_cfgs(2);
5583         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5584         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5585         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5586         // Force duplicate randomness for every get-random call
5587         for node in nodes.iter() {
5588                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5589         }
5590
5591         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5592         let channel_value_satoshis=10000;
5593         let push_msat=10001;
5594         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5595         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5596         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5597         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5598
5599         // Create a second channel with the same random values. This used to panic due to a colliding
5600         // channel_id, but now panics due to a colliding outbound SCID alias.
5601         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5602 }
5603
5604 #[test]
5605 fn bolt2_open_channel_sending_node_checks_part2() {
5606         let chanmon_cfgs = create_chanmon_cfgs(2);
5607         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5608         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5609         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5610
5611         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5612         let channel_value_satoshis=2^24;
5613         let push_msat=10001;
5614         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5615
5616         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5617         let channel_value_satoshis=10000;
5618         // Test when push_msat is equal to 1000 * funding_satoshis.
5619         let push_msat=1000*channel_value_satoshis+1;
5620         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5621
5622         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5623         let channel_value_satoshis=10000;
5624         let push_msat=10001;
5625         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
5626         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5627         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5628
5629         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5630         // 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
5631         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5632
5633         // 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.
5634         assert!(BREAKDOWN_TIMEOUT>0);
5635         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5636
5637         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5638         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5639         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5640
5641         // 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.
5642         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5643         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5644         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5645         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5646         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5647 }
5648
5649 #[test]
5650 fn bolt2_open_channel_sane_dust_limit() {
5651         let chanmon_cfgs = create_chanmon_cfgs(2);
5652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5654         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5655
5656         let channel_value_satoshis=1000000;
5657         let push_msat=10001;
5658         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5659         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5660         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5661         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5662
5663         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5664         let events = nodes[1].node.get_and_clear_pending_msg_events();
5665         let err_msg = match events[0] {
5666                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5667                         msg.clone()
5668                 },
5669                 _ => panic!("Unexpected event"),
5670         };
5671         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5672 }
5673
5674 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5675 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5676 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5677 // is no longer affordable once it's freed.
5678 #[test]
5679 fn test_fail_holding_cell_htlc_upon_free() {
5680         let chanmon_cfgs = create_chanmon_cfgs(2);
5681         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5682         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5683         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5685
5686         // First nodes[0] generates an update_fee, setting the channel's
5687         // pending_update_fee.
5688         {
5689                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5690                 *feerate_lock += 20;
5691         }
5692         nodes[0].node.timer_tick_occurred();
5693         check_added_monitors!(nodes[0], 1);
5694
5695         let events = nodes[0].node.get_and_clear_pending_msg_events();
5696         assert_eq!(events.len(), 1);
5697         let (update_msg, commitment_signed) = match events[0] {
5698                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5699                         (update_fee.as_ref(), commitment_signed)
5700                 },
5701                 _ => panic!("Unexpected event"),
5702         };
5703
5704         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5705
5706         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5707         let channel_reserve = chan_stat.channel_reserve_msat;
5708         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5709         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5710
5711         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5712         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5713         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5714
5715         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5716         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5717                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5718         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5719         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5720
5721         // Flush the pending fee update.
5722         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5723         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5724         check_added_monitors!(nodes[1], 1);
5725         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5726         check_added_monitors!(nodes[0], 1);
5727
5728         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5729         // HTLC, but now that the fee has been raised the payment will now fail, causing
5730         // us to surface its failure to the user.
5731         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5732         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5733         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);
5734
5735         // Check that the payment failed to be sent out.
5736         let events = nodes[0].node.get_and_clear_pending_events();
5737         assert_eq!(events.len(), 2);
5738         match &events[0] {
5739                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5740                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5741                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5742                         assert_eq!(*payment_failed_permanently, false);
5743                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5744                 },
5745                 _ => panic!("Unexpected event"),
5746         }
5747         match &events[1] {
5748                 &Event::PaymentFailed { ref payment_hash, .. } => {
5749                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5750                 },
5751                 _ => panic!("Unexpected event"),
5752         }
5753 }
5754
5755 // Test that if multiple HTLCs are released from the holding cell and one is
5756 // valid but the other is no longer valid upon release, the valid HTLC can be
5757 // successfully completed while the other one fails as expected.
5758 #[test]
5759 fn test_free_and_fail_holding_cell_htlcs() {
5760         let chanmon_cfgs = create_chanmon_cfgs(2);
5761         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5762         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5763         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5764         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5765
5766         // First nodes[0] generates an update_fee, setting the channel's
5767         // pending_update_fee.
5768         {
5769                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5770                 *feerate_lock += 200;
5771         }
5772         nodes[0].node.timer_tick_occurred();
5773         check_added_monitors!(nodes[0], 1);
5774
5775         let events = nodes[0].node.get_and_clear_pending_msg_events();
5776         assert_eq!(events.len(), 1);
5777         let (update_msg, commitment_signed) = match events[0] {
5778                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5779                         (update_fee.as_ref(), commitment_signed)
5780                 },
5781                 _ => panic!("Unexpected event"),
5782         };
5783
5784         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5785
5786         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5787         let channel_reserve = chan_stat.channel_reserve_msat;
5788         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5789         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5790
5791         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5792         let amt_1 = 20000;
5793         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5794         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5795         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5796
5797         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5798         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5799                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5800         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5801         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5802         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5803         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5804                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5805         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5806         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5807
5808         // Flush the pending fee update.
5809         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5810         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5811         check_added_monitors!(nodes[1], 1);
5812         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5813         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5814         check_added_monitors!(nodes[0], 2);
5815
5816         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5817         // but now that the fee has been raised the second payment will now fail, causing us
5818         // to surface its failure to the user. The first payment should succeed.
5819         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5820         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5821         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);
5822
5823         // Check that the second payment failed to be sent out.
5824         let events = nodes[0].node.get_and_clear_pending_events();
5825         assert_eq!(events.len(), 2);
5826         match &events[0] {
5827                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5828                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5829                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5830                         assert_eq!(*payment_failed_permanently, false);
5831                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5832                 },
5833                 _ => panic!("Unexpected event"),
5834         }
5835         match &events[1] {
5836                 &Event::PaymentFailed { ref payment_hash, .. } => {
5837                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5838                 },
5839                 _ => panic!("Unexpected event"),
5840         }
5841
5842         // Complete the first payment and the RAA from the fee update.
5843         let (payment_event, send_raa_event) = {
5844                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5845                 assert_eq!(msgs.len(), 2);
5846                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5847         };
5848         let raa = match send_raa_event {
5849                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5850                 _ => panic!("Unexpected event"),
5851         };
5852         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5853         check_added_monitors!(nodes[1], 1);
5854         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5855         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5856         let events = nodes[1].node.get_and_clear_pending_events();
5857         assert_eq!(events.len(), 1);
5858         match events[0] {
5859                 Event::PendingHTLCsForwardable { .. } => {},
5860                 _ => panic!("Unexpected event"),
5861         }
5862         nodes[1].node.process_pending_htlc_forwards();
5863         let events = nodes[1].node.get_and_clear_pending_events();
5864         assert_eq!(events.len(), 1);
5865         match events[0] {
5866                 Event::PaymentClaimable { .. } => {},
5867                 _ => panic!("Unexpected event"),
5868         }
5869         nodes[1].node.claim_funds(payment_preimage_1);
5870         check_added_monitors!(nodes[1], 1);
5871         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5872
5873         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5874         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5875         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5876         expect_payment_sent!(nodes[0], payment_preimage_1);
5877 }
5878
5879 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5880 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5881 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5882 // once it's freed.
5883 #[test]
5884 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5885         let chanmon_cfgs = create_chanmon_cfgs(3);
5886         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5887         // Avoid having to include routing fees in calculations
5888         let mut config = test_default_channel_config();
5889         config.channel_config.forwarding_fee_base_msat = 0;
5890         config.channel_config.forwarding_fee_proportional_millionths = 0;
5891         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5892         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5893         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5894         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5895
5896         // First nodes[1] generates an update_fee, setting the channel's
5897         // pending_update_fee.
5898         {
5899                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5900                 *feerate_lock += 20;
5901         }
5902         nodes[1].node.timer_tick_occurred();
5903         check_added_monitors!(nodes[1], 1);
5904
5905         let events = nodes[1].node.get_and_clear_pending_msg_events();
5906         assert_eq!(events.len(), 1);
5907         let (update_msg, commitment_signed) = match events[0] {
5908                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5909                         (update_fee.as_ref(), commitment_signed)
5910                 },
5911                 _ => panic!("Unexpected event"),
5912         };
5913
5914         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5915
5916         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5917         let channel_reserve = chan_stat.channel_reserve_msat;
5918         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5919         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5920
5921         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5922         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5923         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5924         let payment_event = {
5925                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5926                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5927                 check_added_monitors!(nodes[0], 1);
5928
5929                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5930                 assert_eq!(events.len(), 1);
5931
5932                 SendEvent::from_event(events.remove(0))
5933         };
5934         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5935         check_added_monitors!(nodes[1], 0);
5936         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5937         expect_pending_htlcs_forwardable!(nodes[1]);
5938
5939         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5940         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5941
5942         // Flush the pending fee update.
5943         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5944         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5945         check_added_monitors!(nodes[2], 1);
5946         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5947         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5948         check_added_monitors!(nodes[1], 2);
5949
5950         // A final RAA message is generated to finalize the fee update.
5951         let events = nodes[1].node.get_and_clear_pending_msg_events();
5952         assert_eq!(events.len(), 1);
5953
5954         let raa_msg = match &events[0] {
5955                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5956                         msg.clone()
5957                 },
5958                 _ => panic!("Unexpected event"),
5959         };
5960
5961         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5962         check_added_monitors!(nodes[2], 1);
5963         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5964
5965         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5966         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5967         assert_eq!(process_htlc_forwards_event.len(), 2);
5968         match &process_htlc_forwards_event[0] {
5969                 &Event::PendingHTLCsForwardable { .. } => {},
5970                 _ => panic!("Unexpected event"),
5971         }
5972
5973         // In response, we call ChannelManager's process_pending_htlc_forwards
5974         nodes[1].node.process_pending_htlc_forwards();
5975         check_added_monitors!(nodes[1], 1);
5976
5977         // This causes the HTLC to be failed backwards.
5978         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5979         assert_eq!(fail_event.len(), 1);
5980         let (fail_msg, commitment_signed) = match &fail_event[0] {
5981                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5982                         assert_eq!(updates.update_add_htlcs.len(), 0);
5983                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5984                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5985                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5986                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5987                 },
5988                 _ => panic!("Unexpected event"),
5989         };
5990
5991         // Pass the failure messages back to nodes[0].
5992         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5993         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5994
5995         // Complete the HTLC failure+removal process.
5996         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5997         check_added_monitors!(nodes[0], 1);
5998         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5999         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6000         check_added_monitors!(nodes[1], 2);
6001         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6002         assert_eq!(final_raa_event.len(), 1);
6003         let raa = match &final_raa_event[0] {
6004                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6005                 _ => panic!("Unexpected event"),
6006         };
6007         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6008         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6009         check_added_monitors!(nodes[0], 1);
6010 }
6011
6012 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6013 // 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.
6014 //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.
6015
6016 #[test]
6017 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6018         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6019         let chanmon_cfgs = create_chanmon_cfgs(2);
6020         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6021         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6022         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6023         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6024
6025         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6026         route.paths[0].hops[0].fee_msat = 100;
6027
6028         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6029                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6030                 ), true, APIError::ChannelUnavailable { .. }, {});
6031         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6032 }
6033
6034 #[test]
6035 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6036         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6037         let chanmon_cfgs = create_chanmon_cfgs(2);
6038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6040         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6041         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6042
6043         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6044         route.paths[0].hops[0].fee_msat = 0;
6045         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6046                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6047                 true, APIError::ChannelUnavailable { ref err },
6048                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6049
6050         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6051         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6052 }
6053
6054 #[test]
6055 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6056         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6057         let chanmon_cfgs = create_chanmon_cfgs(2);
6058         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6059         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6060         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6061         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6062
6063         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6064         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6065                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6066         check_added_monitors!(nodes[0], 1);
6067         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6068         updates.update_add_htlcs[0].amount_msat = 0;
6069
6070         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6071         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6072         check_closed_broadcast!(nodes[1], true).unwrap();
6073         check_added_monitors!(nodes[1], 1);
6074         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6075 }
6076
6077 #[test]
6078 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6079         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6080         //It is enforced when constructing a route.
6081         let chanmon_cfgs = create_chanmon_cfgs(2);
6082         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6083         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6084         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6085         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6086
6087         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6088                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6089         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6090         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6091         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6092                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6093                 ), true, APIError::InvalidRoute { ref err },
6094                 assert_eq!(err, &"Channel CLTV overflowed?"));
6095 }
6096
6097 #[test]
6098 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6099         //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.
6100         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6101         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6102         let chanmon_cfgs = create_chanmon_cfgs(2);
6103         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6104         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6105         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6106         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6107         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6108                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6109
6110         // Fetch a route in advance as we will be unable to once we're unable to send.
6111         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6112         for i in 0..max_accepted_htlcs {
6113                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6114                 let payment_event = {
6115                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6116                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6117                         check_added_monitors!(nodes[0], 1);
6118
6119                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6120                         assert_eq!(events.len(), 1);
6121                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6122                                 assert_eq!(htlcs[0].htlc_id, i);
6123                         } else {
6124                                 assert!(false);
6125                         }
6126                         SendEvent::from_event(events.remove(0))
6127                 };
6128                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6129                 check_added_monitors!(nodes[1], 0);
6130                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6131
6132                 expect_pending_htlcs_forwardable!(nodes[1]);
6133                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6134         }
6135         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6136                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6137                 ), true, APIError::ChannelUnavailable { .. }, {});
6138
6139         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6140 }
6141
6142 #[test]
6143 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6144         //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.
6145         let chanmon_cfgs = create_chanmon_cfgs(2);
6146         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6147         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6148         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6149         let channel_value = 100000;
6150         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6151         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6152
6153         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6154
6155         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6156         // Manually create a route over our max in flight (which our router normally automatically
6157         // limits us to.
6158         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6159         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6160                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6161                 ), true, APIError::ChannelUnavailable { .. }, {});
6162         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6163
6164         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6165 }
6166
6167 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6168 #[test]
6169 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6170         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6171         let chanmon_cfgs = create_chanmon_cfgs(2);
6172         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6173         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6174         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6175         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6176         let htlc_minimum_msat: u64;
6177         {
6178                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6179                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6180                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6181                 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6182         }
6183
6184         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6185         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6186                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6187         check_added_monitors!(nodes[0], 1);
6188         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6189         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6190         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6191         assert!(nodes[1].node.list_channels().is_empty());
6192         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6193         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()));
6194         check_added_monitors!(nodes[1], 1);
6195         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6196 }
6197
6198 #[test]
6199 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6200         //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
6201         let chanmon_cfgs = create_chanmon_cfgs(2);
6202         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6203         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6204         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6205         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6206
6207         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6208         let channel_reserve = chan_stat.channel_reserve_msat;
6209         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6210         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6211         // The 2* and +1 are for the fee spike reserve.
6212         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6213
6214         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6215         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6216         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6217                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6218         check_added_monitors!(nodes[0], 1);
6219         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6220
6221         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6222         // at this time channel-initiatee receivers are not required to enforce that senders
6223         // respect the fee_spike_reserve.
6224         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6225         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6226
6227         assert!(nodes[1].node.list_channels().is_empty());
6228         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6229         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6230         check_added_monitors!(nodes[1], 1);
6231         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6232 }
6233
6234 #[test]
6235 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6236         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6237         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6238         let chanmon_cfgs = create_chanmon_cfgs(2);
6239         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6240         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6241         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6242         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6243
6244         let send_amt = 3999999;
6245         let (mut route, our_payment_hash, _, our_payment_secret) =
6246                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6247         route.paths[0].hops[0].fee_msat = send_amt;
6248         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6249         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6250         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6251         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6252                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6253         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6254
6255         let mut msg = msgs::UpdateAddHTLC {
6256                 channel_id: chan.2,
6257                 htlc_id: 0,
6258                 amount_msat: 1000,
6259                 payment_hash: our_payment_hash,
6260                 cltv_expiry: htlc_cltv,
6261                 onion_routing_packet: onion_packet.clone(),
6262         };
6263
6264         for i in 0..50 {
6265                 msg.htlc_id = i as u64;
6266                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6267         }
6268         msg.htlc_id = (50) as u64;
6269         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6270
6271         assert!(nodes[1].node.list_channels().is_empty());
6272         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6273         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6274         check_added_monitors!(nodes[1], 1);
6275         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6276 }
6277
6278 #[test]
6279 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6280         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6281         let chanmon_cfgs = create_chanmon_cfgs(2);
6282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6284         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6285         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6286
6287         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6288         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6289                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6290         check_added_monitors!(nodes[0], 1);
6291         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6292         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;
6293         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6294
6295         assert!(nodes[1].node.list_channels().is_empty());
6296         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6297         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6298         check_added_monitors!(nodes[1], 1);
6299         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6300 }
6301
6302 #[test]
6303 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6304         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6305         let chanmon_cfgs = create_chanmon_cfgs(2);
6306         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6307         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6308         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6309
6310         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6311         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6312         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6313                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6314         check_added_monitors!(nodes[0], 1);
6315         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6316         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6317         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6318
6319         assert!(nodes[1].node.list_channels().is_empty());
6320         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6321         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6322         check_added_monitors!(nodes[1], 1);
6323         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6324 }
6325
6326 #[test]
6327 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6328         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6329         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6330         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6331         let chanmon_cfgs = create_chanmon_cfgs(2);
6332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6334         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6335
6336         create_announced_chan_between_nodes(&nodes, 0, 1);
6337         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6338         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6339                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6340         check_added_monitors!(nodes[0], 1);
6341         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6342         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6343
6344         //Disconnect and Reconnect
6345         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6346         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6347         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6348                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6349         }, true).unwrap();
6350         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6351         assert_eq!(reestablish_1.len(), 1);
6352         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6353                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6354         }, false).unwrap();
6355         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6356         assert_eq!(reestablish_2.len(), 1);
6357         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6358         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6359         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6360         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6361
6362         //Resend HTLC
6363         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6364         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6365         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6366         check_added_monitors!(nodes[1], 1);
6367         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6368
6369         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6370
6371         assert!(nodes[1].node.list_channels().is_empty());
6372         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6373         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6374         check_added_monitors!(nodes[1], 1);
6375         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6376 }
6377
6378 #[test]
6379 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6380         //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.
6381
6382         let chanmon_cfgs = create_chanmon_cfgs(2);
6383         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6384         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6385         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6386         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6387         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6388         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6389                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6390
6391         check_added_monitors!(nodes[0], 1);
6392         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6393         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6394
6395         let update_msg = msgs::UpdateFulfillHTLC{
6396                 channel_id: chan.2,
6397                 htlc_id: 0,
6398                 payment_preimage: our_payment_preimage,
6399         };
6400
6401         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6402
6403         assert!(nodes[0].node.list_channels().is_empty());
6404         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6405         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()));
6406         check_added_monitors!(nodes[0], 1);
6407         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6408 }
6409
6410 #[test]
6411 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6412         //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.
6413
6414         let chanmon_cfgs = create_chanmon_cfgs(2);
6415         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6416         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6417         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6418         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6419
6420         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6421         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6422                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6423         check_added_monitors!(nodes[0], 1);
6424         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6425         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6426
6427         let update_msg = msgs::UpdateFailHTLC{
6428                 channel_id: chan.2,
6429                 htlc_id: 0,
6430                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6431         };
6432
6433         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6434
6435         assert!(nodes[0].node.list_channels().is_empty());
6436         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6437         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()));
6438         check_added_monitors!(nodes[0], 1);
6439         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6440 }
6441
6442 #[test]
6443 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6444         //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.
6445
6446         let chanmon_cfgs = create_chanmon_cfgs(2);
6447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6449         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6450         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6451
6452         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6453         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6454                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6455         check_added_monitors!(nodes[0], 1);
6456         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6457         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6458         let update_msg = msgs::UpdateFailMalformedHTLC{
6459                 channel_id: chan.2,
6460                 htlc_id: 0,
6461                 sha256_of_onion: [1; 32],
6462                 failure_code: 0x8000,
6463         };
6464
6465         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6466
6467         assert!(nodes[0].node.list_channels().is_empty());
6468         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6469         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()));
6470         check_added_monitors!(nodes[0], 1);
6471         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6472 }
6473
6474 #[test]
6475 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6476         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6477
6478         let chanmon_cfgs = create_chanmon_cfgs(2);
6479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6481         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6482         create_announced_chan_between_nodes(&nodes, 0, 1);
6483
6484         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6485
6486         nodes[1].node.claim_funds(our_payment_preimage);
6487         check_added_monitors!(nodes[1], 1);
6488         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6489
6490         let events = nodes[1].node.get_and_clear_pending_msg_events();
6491         assert_eq!(events.len(), 1);
6492         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6493                 match events[0] {
6494                         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, .. } } => {
6495                                 assert!(update_add_htlcs.is_empty());
6496                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6497                                 assert!(update_fail_htlcs.is_empty());
6498                                 assert!(update_fail_malformed_htlcs.is_empty());
6499                                 assert!(update_fee.is_none());
6500                                 update_fulfill_htlcs[0].clone()
6501                         },
6502                         _ => panic!("Unexpected event"),
6503                 }
6504         };
6505
6506         update_fulfill_msg.htlc_id = 1;
6507
6508         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6509
6510         assert!(nodes[0].node.list_channels().is_empty());
6511         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6512         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6513         check_added_monitors!(nodes[0], 1);
6514         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6515 }
6516
6517 #[test]
6518 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6519         //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.
6520
6521         let chanmon_cfgs = create_chanmon_cfgs(2);
6522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6525         create_announced_chan_between_nodes(&nodes, 0, 1);
6526
6527         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6528
6529         nodes[1].node.claim_funds(our_payment_preimage);
6530         check_added_monitors!(nodes[1], 1);
6531         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6532
6533         let events = nodes[1].node.get_and_clear_pending_msg_events();
6534         assert_eq!(events.len(), 1);
6535         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6536                 match events[0] {
6537                         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, .. } } => {
6538                                 assert!(update_add_htlcs.is_empty());
6539                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6540                                 assert!(update_fail_htlcs.is_empty());
6541                                 assert!(update_fail_malformed_htlcs.is_empty());
6542                                 assert!(update_fee.is_none());
6543                                 update_fulfill_htlcs[0].clone()
6544                         },
6545                         _ => panic!("Unexpected event"),
6546                 }
6547         };
6548
6549         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6550
6551         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6552
6553         assert!(nodes[0].node.list_channels().is_empty());
6554         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6555         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6556         check_added_monitors!(nodes[0], 1);
6557         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6558 }
6559
6560 #[test]
6561 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6562         //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.
6563
6564         let chanmon_cfgs = create_chanmon_cfgs(2);
6565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6567         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6568         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6569
6570         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6571         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6572                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6573         check_added_monitors!(nodes[0], 1);
6574
6575         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6576         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6577
6578         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6579         check_added_monitors!(nodes[1], 0);
6580         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6581
6582         let events = nodes[1].node.get_and_clear_pending_msg_events();
6583
6584         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6585                 match events[0] {
6586                         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, .. } } => {
6587                                 assert!(update_add_htlcs.is_empty());
6588                                 assert!(update_fulfill_htlcs.is_empty());
6589                                 assert!(update_fail_htlcs.is_empty());
6590                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6591                                 assert!(update_fee.is_none());
6592                                 update_fail_malformed_htlcs[0].clone()
6593                         },
6594                         _ => panic!("Unexpected event"),
6595                 }
6596         };
6597         update_msg.failure_code &= !0x8000;
6598         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6599
6600         assert!(nodes[0].node.list_channels().is_empty());
6601         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6602         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6603         check_added_monitors!(nodes[0], 1);
6604         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6605 }
6606
6607 #[test]
6608 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6609         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6610         //    * 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.
6611
6612         let chanmon_cfgs = create_chanmon_cfgs(3);
6613         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6614         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6615         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6616         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6617         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6618
6619         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6620
6621         //First hop
6622         let mut payment_event = {
6623                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6624                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6625                 check_added_monitors!(nodes[0], 1);
6626                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6627                 assert_eq!(events.len(), 1);
6628                 SendEvent::from_event(events.remove(0))
6629         };
6630         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6631         check_added_monitors!(nodes[1], 0);
6632         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6633         expect_pending_htlcs_forwardable!(nodes[1]);
6634         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6635         assert_eq!(events_2.len(), 1);
6636         check_added_monitors!(nodes[1], 1);
6637         payment_event = SendEvent::from_event(events_2.remove(0));
6638         assert_eq!(payment_event.msgs.len(), 1);
6639
6640         //Second Hop
6641         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6642         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6643         check_added_monitors!(nodes[2], 0);
6644         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6645
6646         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6647         assert_eq!(events_3.len(), 1);
6648         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6649                 match events_3[0] {
6650                         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 } } => {
6651                                 assert!(update_add_htlcs.is_empty());
6652                                 assert!(update_fulfill_htlcs.is_empty());
6653                                 assert!(update_fail_htlcs.is_empty());
6654                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6655                                 assert!(update_fee.is_none());
6656                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6657                         },
6658                         _ => panic!("Unexpected event"),
6659                 }
6660         };
6661
6662         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6663
6664         check_added_monitors!(nodes[1], 0);
6665         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6666         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 }]);
6667         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6668         assert_eq!(events_4.len(), 1);
6669
6670         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6671         match events_4[0] {
6672                 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, .. } } => {
6673                         assert!(update_add_htlcs.is_empty());
6674                         assert!(update_fulfill_htlcs.is_empty());
6675                         assert_eq!(update_fail_htlcs.len(), 1);
6676                         assert!(update_fail_malformed_htlcs.is_empty());
6677                         assert!(update_fee.is_none());
6678                 },
6679                 _ => panic!("Unexpected event"),
6680         };
6681
6682         check_added_monitors!(nodes[1], 1);
6683 }
6684
6685 #[test]
6686 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6687         let chanmon_cfgs = create_chanmon_cfgs(3);
6688         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6689         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6690         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6691         create_announced_chan_between_nodes(&nodes, 0, 1);
6692         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6693
6694         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6695
6696         // First hop
6697         let mut payment_event = {
6698                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6699                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6700                 check_added_monitors!(nodes[0], 1);
6701                 SendEvent::from_node(&nodes[0])
6702         };
6703
6704         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6705         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6706         expect_pending_htlcs_forwardable!(nodes[1]);
6707         check_added_monitors!(nodes[1], 1);
6708         payment_event = SendEvent::from_node(&nodes[1]);
6709         assert_eq!(payment_event.msgs.len(), 1);
6710
6711         // Second Hop
6712         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6713         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6714         check_added_monitors!(nodes[2], 0);
6715         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6716
6717         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6718         assert_eq!(events_3.len(), 1);
6719         match events_3[0] {
6720                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6721                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6722                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6723                         update_msg.failure_code |= 0x2000;
6724
6725                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6726                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6727                 },
6728                 _ => panic!("Unexpected event"),
6729         }
6730
6731         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6732                 vec![HTLCDestination::NextHopChannel {
6733                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6734         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6735         assert_eq!(events_4.len(), 1);
6736         check_added_monitors!(nodes[1], 1);
6737
6738         match events_4[0] {
6739                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6740                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6741                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6742                 },
6743                 _ => panic!("Unexpected event"),
6744         }
6745
6746         let events_5 = nodes[0].node.get_and_clear_pending_events();
6747         assert_eq!(events_5.len(), 2);
6748
6749         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6750         // the node originating the error to its next hop.
6751         match events_5[0] {
6752                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6753                 } => {
6754                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6755                         assert!(is_permanent);
6756                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6757                 },
6758                 _ => panic!("Unexpected event"),
6759         }
6760         match events_5[1] {
6761                 Event::PaymentFailed { payment_hash, .. } => {
6762                         assert_eq!(payment_hash, our_payment_hash);
6763                 },
6764                 _ => panic!("Unexpected event"),
6765         }
6766
6767         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6768 }
6769
6770 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6771         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6772         // 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
6773         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6774
6775         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6776         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6778         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6779         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6780         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6781
6782         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6783                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6784
6785         // We route 2 dust-HTLCs between A and B
6786         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6787         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6788         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6789
6790         // Cache one local commitment tx as previous
6791         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6792
6793         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6794         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6795         check_added_monitors!(nodes[1], 0);
6796         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6797         check_added_monitors!(nodes[1], 1);
6798
6799         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6800         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6801         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6802         check_added_monitors!(nodes[0], 1);
6803
6804         // Cache one local commitment tx as lastest
6805         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6806
6807         let events = nodes[0].node.get_and_clear_pending_msg_events();
6808         match events[0] {
6809                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6810                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6811                 },
6812                 _ => panic!("Unexpected event"),
6813         }
6814         match events[1] {
6815                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6816                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6817                 },
6818                 _ => panic!("Unexpected event"),
6819         }
6820
6821         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6822         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6823         if announce_latest {
6824                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6825         } else {
6826                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6827         }
6828
6829         check_closed_broadcast!(nodes[0], true);
6830         check_added_monitors!(nodes[0], 1);
6831         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6832
6833         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6834         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6835         let events = nodes[0].node.get_and_clear_pending_events();
6836         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6837         assert_eq!(events.len(), 4);
6838         let mut first_failed = false;
6839         for event in events {
6840                 match event {
6841                         Event::PaymentPathFailed { payment_hash, .. } => {
6842                                 if payment_hash == payment_hash_1 {
6843                                         assert!(!first_failed);
6844                                         first_failed = true;
6845                                 } else {
6846                                         assert_eq!(payment_hash, payment_hash_2);
6847                                 }
6848                         },
6849                         Event::PaymentFailed { .. } => {}
6850                         _ => panic!("Unexpected event"),
6851                 }
6852         }
6853 }
6854
6855 #[test]
6856 fn test_failure_delay_dust_htlc_local_commitment() {
6857         do_test_failure_delay_dust_htlc_local_commitment(true);
6858         do_test_failure_delay_dust_htlc_local_commitment(false);
6859 }
6860
6861 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6862         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6863         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6864         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6865         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6866         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6867         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6868
6869         let chanmon_cfgs = create_chanmon_cfgs(3);
6870         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6871         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6872         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6873         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6874
6875         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6876                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6877
6878         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6879         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6880
6881         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6882         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6883
6884         // We revoked bs_commitment_tx
6885         if revoked {
6886                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6887                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6888         }
6889
6890         let mut timeout_tx = Vec::new();
6891         if local {
6892                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6893                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6894                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6895                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6896                 expect_payment_failed!(nodes[0], dust_hash, false);
6897
6898                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6899                 check_closed_broadcast!(nodes[0], true);
6900                 check_added_monitors!(nodes[0], 1);
6901                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6902                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6903                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6904                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6905                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6906                 mine_transaction(&nodes[0], &timeout_tx[0]);
6907                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6908                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6909         } else {
6910                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6911                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6912                 check_closed_broadcast!(nodes[0], true);
6913                 check_added_monitors!(nodes[0], 1);
6914                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6915                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6916
6917                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6918                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6919                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6920                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6921                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6922                 // dust HTLC should have been failed.
6923                 expect_payment_failed!(nodes[0], dust_hash, false);
6924
6925                 if !revoked {
6926                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6927                 } else {
6928                         assert_eq!(timeout_tx[0].lock_time.0, 11);
6929                 }
6930                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6931                 mine_transaction(&nodes[0], &timeout_tx[0]);
6932                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6933                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6934                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6935         }
6936 }
6937
6938 #[test]
6939 fn test_sweep_outbound_htlc_failure_update() {
6940         do_test_sweep_outbound_htlc_failure_update(false, true);
6941         do_test_sweep_outbound_htlc_failure_update(false, false);
6942         do_test_sweep_outbound_htlc_failure_update(true, false);
6943 }
6944
6945 #[test]
6946 fn test_user_configurable_csv_delay() {
6947         // We test our channel constructors yield errors when we pass them absurd csv delay
6948
6949         let mut low_our_to_self_config = UserConfig::default();
6950         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6951         let mut high_their_to_self_config = UserConfig::default();
6952         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6953         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6954         let chanmon_cfgs = create_chanmon_cfgs(2);
6955         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6956         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6957         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6958
6959         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
6960         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6961                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6962                 &low_our_to_self_config, 0, 42)
6963         {
6964                 match error {
6965                         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())); },
6966                         _ => panic!("Unexpected event"),
6967                 }
6968         } else { assert!(false) }
6969
6970         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new_from_req()
6971         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6972         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6973         open_channel.to_self_delay = 200;
6974         if let Err(error) = InboundV1Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6975                 &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,
6976                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6977         {
6978                 match error {
6979                         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()));  },
6980                         _ => panic!("Unexpected event"),
6981                 }
6982         } else { assert!(false); }
6983
6984         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6985         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6986         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()));
6987         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6988         accept_channel.to_self_delay = 200;
6989         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6990         let reason_msg;
6991         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6992                 match action {
6993                         &ErrorAction::SendErrorMessage { ref msg } => {
6994                                 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()));
6995                                 reason_msg = msg.data.clone();
6996                         },
6997                         _ => { panic!(); }
6998                 }
6999         } else { panic!(); }
7000         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7001
7002         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new_from_req()
7003         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7004         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7005         open_channel.to_self_delay = 200;
7006         if let Err(error) = InboundV1Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7007                 &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,
7008                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7009         {
7010                 match error {
7011                         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())); },
7012                         _ => panic!("Unexpected event"),
7013                 }
7014         } else { assert!(false); }
7015 }
7016
7017 #[test]
7018 fn test_check_htlc_underpaying() {
7019         // Send payment through A -> B but A is maliciously
7020         // sending a probe payment (i.e less than expected value0
7021         // to B, B should refuse payment.
7022
7023         let chanmon_cfgs = create_chanmon_cfgs(2);
7024         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7025         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7026         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7027
7028         // Create some initial channels
7029         create_announced_chan_between_nodes(&nodes, 0, 1);
7030
7031         let scorer = test_utils::TestScorer::new();
7032         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7033         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();
7034         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();
7035         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7036         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7037         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7038                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7039         check_added_monitors!(nodes[0], 1);
7040
7041         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7042         assert_eq!(events.len(), 1);
7043         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7044         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7045         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7046
7047         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7048         // and then will wait a second random delay before failing the HTLC back:
7049         expect_pending_htlcs_forwardable!(nodes[1]);
7050         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7051
7052         // Node 3 is expecting payment of 100_000 but received 10_000,
7053         // it should fail htlc like we didn't know the preimage.
7054         nodes[1].node.process_pending_htlc_forwards();
7055
7056         let events = nodes[1].node.get_and_clear_pending_msg_events();
7057         assert_eq!(events.len(), 1);
7058         let (update_fail_htlc, commitment_signed) = match events[0] {
7059                 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 } } => {
7060                         assert!(update_add_htlcs.is_empty());
7061                         assert!(update_fulfill_htlcs.is_empty());
7062                         assert_eq!(update_fail_htlcs.len(), 1);
7063                         assert!(update_fail_malformed_htlcs.is_empty());
7064                         assert!(update_fee.is_none());
7065                         (update_fail_htlcs[0].clone(), commitment_signed)
7066                 },
7067                 _ => panic!("Unexpected event"),
7068         };
7069         check_added_monitors!(nodes[1], 1);
7070
7071         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7072         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7073
7074         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7075         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7076         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7077         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7078 }
7079
7080 #[test]
7081 fn test_announce_disable_channels() {
7082         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7083         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7084
7085         let chanmon_cfgs = create_chanmon_cfgs(2);
7086         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7087         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7088         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7089
7090         create_announced_chan_between_nodes(&nodes, 0, 1);
7091         create_announced_chan_between_nodes(&nodes, 1, 0);
7092         create_announced_chan_between_nodes(&nodes, 0, 1);
7093
7094         // Disconnect peers
7095         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7096         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7097
7098         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7099                 nodes[0].node.timer_tick_occurred();
7100         }
7101         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7102         assert_eq!(msg_events.len(), 3);
7103         let mut chans_disabled = HashMap::new();
7104         for e in msg_events {
7105                 match e {
7106                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7107                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7108                                 // Check that each channel gets updated exactly once
7109                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7110                                         panic!("Generated ChannelUpdate for wrong chan!");
7111                                 }
7112                         },
7113                         _ => panic!("Unexpected event"),
7114                 }
7115         }
7116         // Reconnect peers
7117         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7118                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7119         }, true).unwrap();
7120         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7121         assert_eq!(reestablish_1.len(), 3);
7122         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7123                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7124         }, false).unwrap();
7125         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7126         assert_eq!(reestablish_2.len(), 3);
7127
7128         // Reestablish chan_1
7129         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7130         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7131         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7132         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7133         // Reestablish chan_2
7134         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7135         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7136         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7137         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7138         // Reestablish chan_3
7139         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7140         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7141         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7142         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7143
7144         for _ in 0..ENABLE_GOSSIP_TICKS {
7145                 nodes[0].node.timer_tick_occurred();
7146         }
7147         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7148         nodes[0].node.timer_tick_occurred();
7149         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7150         assert_eq!(msg_events.len(), 3);
7151         for e in msg_events {
7152                 match e {
7153                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7154                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7155                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7156                                         // Each update should have a higher timestamp than the previous one, replacing
7157                                         // the old one.
7158                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7159                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7160                                 }
7161                         },
7162                         _ => panic!("Unexpected event"),
7163                 }
7164         }
7165         // Check that each channel gets updated exactly once
7166         assert!(chans_disabled.is_empty());
7167 }
7168
7169 #[test]
7170 fn test_bump_penalty_txn_on_revoked_commitment() {
7171         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7172         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7173
7174         let chanmon_cfgs = create_chanmon_cfgs(2);
7175         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7176         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7177         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7178
7179         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7180
7181         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7182         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7183                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7184         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7185         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7186
7187         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7188         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7189         assert_eq!(revoked_txn[0].output.len(), 4);
7190         assert_eq!(revoked_txn[0].input.len(), 1);
7191         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7192         let revoked_txid = revoked_txn[0].txid();
7193
7194         let mut penalty_sum = 0;
7195         for outp in revoked_txn[0].output.iter() {
7196                 if outp.script_pubkey.is_v0_p2wsh() {
7197                         penalty_sum += outp.value;
7198                 }
7199         }
7200
7201         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7202         let header_114 = connect_blocks(&nodes[1], 14);
7203
7204         // Actually revoke tx by claiming a HTLC
7205         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7206         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7207         check_added_monitors!(nodes[1], 1);
7208
7209         // One or more justice tx should have been broadcast, check it
7210         let penalty_1;
7211         let feerate_1;
7212         {
7213                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7214                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7215                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7216                 assert_eq!(node_txn[0].output.len(), 1);
7217                 check_spends!(node_txn[0], revoked_txn[0]);
7218                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7219                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7220                 penalty_1 = node_txn[0].txid();
7221                 node_txn.clear();
7222         };
7223
7224         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7225         connect_blocks(&nodes[1], 15);
7226         let mut penalty_2 = penalty_1;
7227         let mut feerate_2 = 0;
7228         {
7229                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7230                 assert_eq!(node_txn.len(), 1);
7231                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7232                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7233                         assert_eq!(node_txn[0].output.len(), 1);
7234                         check_spends!(node_txn[0], revoked_txn[0]);
7235                         penalty_2 = node_txn[0].txid();
7236                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7237                         assert_ne!(penalty_2, penalty_1);
7238                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7239                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7240                         // Verify 25% bump heuristic
7241                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7242                         node_txn.clear();
7243                 }
7244         }
7245         assert_ne!(feerate_2, 0);
7246
7247         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7248         connect_blocks(&nodes[1], 1);
7249         let penalty_3;
7250         let mut feerate_3 = 0;
7251         {
7252                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7253                 assert_eq!(node_txn.len(), 1);
7254                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7255                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7256                         assert_eq!(node_txn[0].output.len(), 1);
7257                         check_spends!(node_txn[0], revoked_txn[0]);
7258                         penalty_3 = node_txn[0].txid();
7259                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7260                         assert_ne!(penalty_3, penalty_2);
7261                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7262                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7263                         // Verify 25% bump heuristic
7264                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7265                         node_txn.clear();
7266                 }
7267         }
7268         assert_ne!(feerate_3, 0);
7269
7270         nodes[1].node.get_and_clear_pending_events();
7271         nodes[1].node.get_and_clear_pending_msg_events();
7272 }
7273
7274 #[test]
7275 fn test_bump_penalty_txn_on_revoked_htlcs() {
7276         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7277         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7278
7279         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7280         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7281         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7282         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7283         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7284
7285         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7286         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7287         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7288         let scorer = test_utils::TestScorer::new();
7289         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7290         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7291                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7292         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7293         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7294         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7295                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7296         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7297
7298         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7299         assert_eq!(revoked_local_txn[0].input.len(), 1);
7300         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7301
7302         // Revoke local commitment tx
7303         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7304
7305         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7306         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7307         check_closed_broadcast!(nodes[1], true);
7308         check_added_monitors!(nodes[1], 1);
7309         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7310         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7311
7312         let revoked_htlc_txn = {
7313                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7314                 assert_eq!(txn.len(), 2);
7315
7316                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7317                 assert_eq!(txn[0].input.len(), 1);
7318                 check_spends!(txn[0], revoked_local_txn[0]);
7319
7320                 assert_eq!(txn[1].input.len(), 1);
7321                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7322                 assert_eq!(txn[1].output.len(), 1);
7323                 check_spends!(txn[1], revoked_local_txn[0]);
7324
7325                 txn
7326         };
7327
7328         // Broadcast set of revoked txn on A
7329         let hash_128 = connect_blocks(&nodes[0], 40);
7330         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7331         connect_block(&nodes[0], &block_11);
7332         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7333         connect_block(&nodes[0], &block_129);
7334         let events = nodes[0].node.get_and_clear_pending_events();
7335         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7336         match events.last().unwrap() {
7337                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7338                 _ => panic!("Unexpected event"),
7339         }
7340         let first;
7341         let feerate_1;
7342         let penalty_txn;
7343         {
7344                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7345                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7346                 // Verify claim tx are spending revoked HTLC txn
7347
7348                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7349                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7350                 // which are included in the same block (they are broadcasted because we scan the
7351                 // transactions linearly and generate claims as we go, they likely should be removed in the
7352                 // future).
7353                 assert_eq!(node_txn[0].input.len(), 1);
7354                 check_spends!(node_txn[0], revoked_local_txn[0]);
7355                 assert_eq!(node_txn[1].input.len(), 1);
7356                 check_spends!(node_txn[1], revoked_local_txn[0]);
7357                 assert_eq!(node_txn[2].input.len(), 1);
7358                 check_spends!(node_txn[2], revoked_local_txn[0]);
7359
7360                 // Each of the three justice transactions claim a separate (single) output of the three
7361                 // available, which we check here:
7362                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7363                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7364                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7365
7366                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7367                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7368
7369                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7370                 // output, checked above).
7371                 assert_eq!(node_txn[3].input.len(), 2);
7372                 assert_eq!(node_txn[3].output.len(), 1);
7373                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7374
7375                 first = node_txn[3].txid();
7376                 // Store both feerates for later comparison
7377                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7378                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7379                 penalty_txn = vec![node_txn[2].clone()];
7380                 node_txn.clear();
7381         }
7382
7383         // Connect one more block to see if bumped penalty are issued for HTLC txn
7384         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7385         connect_block(&nodes[0], &block_130);
7386         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7387         connect_block(&nodes[0], &block_131);
7388
7389         // Few more blocks to confirm penalty txn
7390         connect_blocks(&nodes[0], 4);
7391         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7392         let header_144 = connect_blocks(&nodes[0], 9);
7393         let node_txn = {
7394                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7395                 assert_eq!(node_txn.len(), 1);
7396
7397                 assert_eq!(node_txn[0].input.len(), 2);
7398                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7399                 // Verify bumped tx is different and 25% bump heuristic
7400                 assert_ne!(first, node_txn[0].txid());
7401                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7402                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7403                 assert!(feerate_2 * 100 > feerate_1 * 125);
7404                 let txn = vec![node_txn[0].clone()];
7405                 node_txn.clear();
7406                 txn
7407         };
7408         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7409         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7410         connect_blocks(&nodes[0], 20);
7411         {
7412                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7413                 // We verify than no new transaction has been broadcast because previously
7414                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7415                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7416                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7417                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7418                 // up bumped justice generation.
7419                 assert_eq!(node_txn.len(), 0);
7420                 node_txn.clear();
7421         }
7422         check_closed_broadcast!(nodes[0], true);
7423         check_added_monitors!(nodes[0], 1);
7424 }
7425
7426 #[test]
7427 fn test_bump_penalty_txn_on_remote_commitment() {
7428         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7429         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7430
7431         // Create 2 HTLCs
7432         // Provide preimage for one
7433         // Check aggregation
7434
7435         let chanmon_cfgs = create_chanmon_cfgs(2);
7436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7439
7440         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7441         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7442         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7443
7444         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7445         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7446         assert_eq!(remote_txn[0].output.len(), 4);
7447         assert_eq!(remote_txn[0].input.len(), 1);
7448         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7449
7450         // Claim a HTLC without revocation (provide B monitor with preimage)
7451         nodes[1].node.claim_funds(payment_preimage);
7452         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7453         mine_transaction(&nodes[1], &remote_txn[0]);
7454         check_added_monitors!(nodes[1], 2);
7455         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7456
7457         // One or more claim tx should have been broadcast, check it
7458         let timeout;
7459         let preimage;
7460         let preimage_bump;
7461         let feerate_timeout;
7462         let feerate_preimage;
7463         {
7464                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7465                 // 3 transactions including:
7466                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7467                 assert_eq!(node_txn.len(), 3);
7468                 assert_eq!(node_txn[0].input.len(), 1);
7469                 assert_eq!(node_txn[1].input.len(), 1);
7470                 assert_eq!(node_txn[2].input.len(), 1);
7471                 check_spends!(node_txn[0], remote_txn[0]);
7472                 check_spends!(node_txn[1], remote_txn[0]);
7473                 check_spends!(node_txn[2], remote_txn[0]);
7474
7475                 preimage = node_txn[0].txid();
7476                 let index = node_txn[0].input[0].previous_output.vout;
7477                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7478                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7479
7480                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7481                         (node_txn[2].clone(), node_txn[1].clone())
7482                 } else {
7483                         (node_txn[1].clone(), node_txn[2].clone())
7484                 };
7485
7486                 preimage_bump = preimage_bump_tx;
7487                 check_spends!(preimage_bump, remote_txn[0]);
7488                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7489
7490                 timeout = timeout_tx.txid();
7491                 let index = timeout_tx.input[0].previous_output.vout;
7492                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7493                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7494
7495                 node_txn.clear();
7496         };
7497         assert_ne!(feerate_timeout, 0);
7498         assert_ne!(feerate_preimage, 0);
7499
7500         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7501         connect_blocks(&nodes[1], 1);
7502         {
7503                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7504                 assert_eq!(node_txn.len(), 1);
7505                 assert_eq!(node_txn[0].input.len(), 1);
7506                 assert_eq!(preimage_bump.input.len(), 1);
7507                 check_spends!(node_txn[0], remote_txn[0]);
7508                 check_spends!(preimage_bump, remote_txn[0]);
7509
7510                 let index = preimage_bump.input[0].previous_output.vout;
7511                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7512                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7513                 assert!(new_feerate * 100 > feerate_timeout * 125);
7514                 assert_ne!(timeout, preimage_bump.txid());
7515
7516                 let index = node_txn[0].input[0].previous_output.vout;
7517                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7518                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7519                 assert!(new_feerate * 100 > feerate_preimage * 125);
7520                 assert_ne!(preimage, node_txn[0].txid());
7521
7522                 node_txn.clear();
7523         }
7524
7525         nodes[1].node.get_and_clear_pending_events();
7526         nodes[1].node.get_and_clear_pending_msg_events();
7527 }
7528
7529 #[test]
7530 fn test_counterparty_raa_skip_no_crash() {
7531         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7532         // commitment transaction, we would have happily carried on and provided them the next
7533         // commitment transaction based on one RAA forward. This would probably eventually have led to
7534         // channel closure, but it would not have resulted in funds loss. Still, our
7535         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7536         // check simply that the channel is closed in response to such an RAA, but don't check whether
7537         // we decide to punish our counterparty for revoking their funds (as we don't currently
7538         // implement that).
7539         let chanmon_cfgs = create_chanmon_cfgs(2);
7540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7542         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7543         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7544
7545         let per_commitment_secret;
7546         let next_per_commitment_point;
7547         {
7548                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7549                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7550                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7551
7552                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7553
7554                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7555                 keys.get_enforcement_state().last_holder_commitment -= 1;
7556                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7557
7558                 // Must revoke without gaps
7559                 keys.get_enforcement_state().last_holder_commitment -= 1;
7560                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7561
7562                 keys.get_enforcement_state().last_holder_commitment -= 1;
7563                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7564                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7565         }
7566
7567         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7568                 &msgs::RevokeAndACK {
7569                         channel_id,
7570                         per_commitment_secret,
7571                         next_per_commitment_point,
7572                         #[cfg(taproot)]
7573                         next_local_nonce: None,
7574                 });
7575         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7576         check_added_monitors!(nodes[1], 1);
7577         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7578 }
7579
7580 #[test]
7581 fn test_bump_txn_sanitize_tracking_maps() {
7582         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7583         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7584
7585         let chanmon_cfgs = create_chanmon_cfgs(2);
7586         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7587         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7588         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7589
7590         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7591         // Lock HTLC in both directions
7592         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7593         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7594
7595         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7596         assert_eq!(revoked_local_txn[0].input.len(), 1);
7597         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7598
7599         // Revoke local commitment tx
7600         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7601
7602         // Broadcast set of revoked txn on A
7603         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7604         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7605         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7606
7607         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7608         check_closed_broadcast!(nodes[0], true);
7609         check_added_monitors!(nodes[0], 1);
7610         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7611         let penalty_txn = {
7612                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7613                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7614                 check_spends!(node_txn[0], revoked_local_txn[0]);
7615                 check_spends!(node_txn[1], revoked_local_txn[0]);
7616                 check_spends!(node_txn[2], revoked_local_txn[0]);
7617                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7618                 node_txn.clear();
7619                 penalty_txn
7620         };
7621         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7622         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7623         {
7624                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7625                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7626                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7627         }
7628 }
7629
7630 #[test]
7631 fn test_channel_conf_timeout() {
7632         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7633         // confirm within 2016 blocks, as recommended by BOLT 2.
7634         let chanmon_cfgs = create_chanmon_cfgs(2);
7635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7637         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7638
7639         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7640
7641         // The outbound node should wait forever for confirmation:
7642         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7643         // copied here instead of directly referencing the constant.
7644         connect_blocks(&nodes[0], 2016);
7645         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7646
7647         // The inbound node should fail the channel after exactly 2016 blocks
7648         connect_blocks(&nodes[1], 2015);
7649         check_added_monitors!(nodes[1], 0);
7650         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7651
7652         connect_blocks(&nodes[1], 1);
7653         check_added_monitors!(nodes[1], 1);
7654         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7655         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7656         assert_eq!(close_ev.len(), 1);
7657         match close_ev[0] {
7658                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7659                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7660                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7661                 },
7662                 _ => panic!("Unexpected event"),
7663         }
7664 }
7665
7666 #[test]
7667 fn test_override_channel_config() {
7668         let chanmon_cfgs = create_chanmon_cfgs(2);
7669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7672
7673         // Node0 initiates a channel to node1 using the override config.
7674         let mut override_config = UserConfig::default();
7675         override_config.channel_handshake_config.our_to_self_delay = 200;
7676
7677         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7678
7679         // Assert the channel created by node0 is using the override config.
7680         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7681         assert_eq!(res.channel_flags, 0);
7682         assert_eq!(res.to_self_delay, 200);
7683 }
7684
7685 #[test]
7686 fn test_override_0msat_htlc_minimum() {
7687         let mut zero_config = UserConfig::default();
7688         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7689         let chanmon_cfgs = create_chanmon_cfgs(2);
7690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7692         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7693
7694         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7695         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7696         assert_eq!(res.htlc_minimum_msat, 1);
7697
7698         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7699         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7700         assert_eq!(res.htlc_minimum_msat, 1);
7701 }
7702
7703 #[test]
7704 fn test_channel_update_has_correct_htlc_maximum_msat() {
7705         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7706         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7707         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7708         // 90% of the `channel_value`.
7709         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7710
7711         let mut config_30_percent = UserConfig::default();
7712         config_30_percent.channel_handshake_config.announced_channel = true;
7713         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7714         let mut config_50_percent = UserConfig::default();
7715         config_50_percent.channel_handshake_config.announced_channel = true;
7716         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7717         let mut config_95_percent = UserConfig::default();
7718         config_95_percent.channel_handshake_config.announced_channel = true;
7719         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7720         let mut config_100_percent = UserConfig::default();
7721         config_100_percent.channel_handshake_config.announced_channel = true;
7722         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7723
7724         let chanmon_cfgs = create_chanmon_cfgs(4);
7725         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7726         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)]);
7727         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7728
7729         let channel_value_satoshis = 100000;
7730         let channel_value_msat = channel_value_satoshis * 1000;
7731         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7732         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7733         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7734
7735         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7736         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7737
7738         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7739         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7740         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7741         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7742         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7743         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7744
7745         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7746         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7747         // `channel_value`.
7748         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7749         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7750         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7751         // `channel_value`.
7752         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7753 }
7754
7755 #[test]
7756 fn test_manually_accept_inbound_channel_request() {
7757         let mut manually_accept_conf = UserConfig::default();
7758         manually_accept_conf.manually_accept_inbound_channels = true;
7759         let chanmon_cfgs = create_chanmon_cfgs(2);
7760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7762         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7763
7764         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7765         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7766
7767         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7768
7769         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7770         // accepting the inbound channel request.
7771         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7772
7773         let events = nodes[1].node.get_and_clear_pending_events();
7774         match events[0] {
7775                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7776                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7777                 }
7778                 _ => panic!("Unexpected event"),
7779         }
7780
7781         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7782         assert_eq!(accept_msg_ev.len(), 1);
7783
7784         match accept_msg_ev[0] {
7785                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7786                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7787                 }
7788                 _ => panic!("Unexpected event"),
7789         }
7790
7791         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7792
7793         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7794         assert_eq!(close_msg_ev.len(), 1);
7795
7796         let events = nodes[1].node.get_and_clear_pending_events();
7797         match events[0] {
7798                 Event::ChannelClosed { user_channel_id, .. } => {
7799                         assert_eq!(user_channel_id, 23);
7800                 }
7801                 _ => panic!("Unexpected event"),
7802         }
7803 }
7804
7805 #[test]
7806 fn test_manually_reject_inbound_channel_request() {
7807         let mut manually_accept_conf = UserConfig::default();
7808         manually_accept_conf.manually_accept_inbound_channels = true;
7809         let chanmon_cfgs = create_chanmon_cfgs(2);
7810         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7811         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7812         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7813
7814         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7815         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7816
7817         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7818
7819         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7820         // rejecting the inbound channel request.
7821         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7822
7823         let events = nodes[1].node.get_and_clear_pending_events();
7824         match events[0] {
7825                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7826                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7827                 }
7828                 _ => panic!("Unexpected event"),
7829         }
7830
7831         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7832         assert_eq!(close_msg_ev.len(), 1);
7833
7834         match close_msg_ev[0] {
7835                 MessageSendEvent::HandleError { ref node_id, .. } => {
7836                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7837                 }
7838                 _ => panic!("Unexpected event"),
7839         }
7840         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7841 }
7842
7843 #[test]
7844 fn test_reject_funding_before_inbound_channel_accepted() {
7845         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7846         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7847         // the node operator before the counterparty sends a `FundingCreated` message. If a
7848         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7849         // and the channel should be closed.
7850         let mut manually_accept_conf = UserConfig::default();
7851         manually_accept_conf.manually_accept_inbound_channels = true;
7852         let chanmon_cfgs = create_chanmon_cfgs(2);
7853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7856
7857         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7858         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7859         let temp_channel_id = res.temporary_channel_id;
7860
7861         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7862
7863         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7864         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7865
7866         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7867         nodes[1].node.get_and_clear_pending_events();
7868
7869         // Get the `AcceptChannel` message of `nodes[1]` without calling
7870         // `ChannelManager::accept_inbound_channel`, which generates a
7871         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7872         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7873         // succeed when `nodes[0]` is passed to it.
7874         let accept_chan_msg = {
7875                 let mut node_1_per_peer_lock;
7876                 let mut node_1_peer_state_lock;
7877                 let channel =  get_inbound_v1_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7878                 channel.get_accept_channel_message()
7879         };
7880         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7881
7882         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7883
7884         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7885         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7886
7887         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7888         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7889
7890         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7891         assert_eq!(close_msg_ev.len(), 1);
7892
7893         let expected_err = "FundingCreated message received before the channel was accepted";
7894         match close_msg_ev[0] {
7895                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7896                         assert_eq!(msg.channel_id, temp_channel_id);
7897                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7898                         assert_eq!(msg.data, expected_err);
7899                 }
7900                 _ => panic!("Unexpected event"),
7901         }
7902
7903         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7904 }
7905
7906 #[test]
7907 fn test_can_not_accept_inbound_channel_twice() {
7908         let mut manually_accept_conf = UserConfig::default();
7909         manually_accept_conf.manually_accept_inbound_channels = true;
7910         let chanmon_cfgs = create_chanmon_cfgs(2);
7911         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7912         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7913         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7914
7915         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7916         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7917
7918         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7919
7920         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7921         // accepting the inbound channel request.
7922         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7923
7924         let events = nodes[1].node.get_and_clear_pending_events();
7925         match events[0] {
7926                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7927                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7928                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7929                         match api_res {
7930                                 Err(APIError::APIMisuseError { err }) => {
7931                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7932                                 },
7933                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7934                                 Err(_) => panic!("Unexpected Error"),
7935                         }
7936                 }
7937                 _ => panic!("Unexpected event"),
7938         }
7939
7940         // Ensure that the channel wasn't closed after attempting to accept it twice.
7941         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7942         assert_eq!(accept_msg_ev.len(), 1);
7943
7944         match accept_msg_ev[0] {
7945                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7946                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7947                 }
7948                 _ => panic!("Unexpected event"),
7949         }
7950 }
7951
7952 #[test]
7953 fn test_can_not_accept_unknown_inbound_channel() {
7954         let chanmon_cfg = create_chanmon_cfgs(2);
7955         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7956         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7957         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7958
7959         let unknown_channel_id = [0; 32];
7960         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7961         match api_res {
7962                 Err(APIError::ChannelUnavailable { err }) => {
7963                         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()));
7964                 },
7965                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7966                 Err(_) => panic!("Unexpected Error"),
7967         }
7968 }
7969
7970 #[test]
7971 fn test_onion_value_mpp_set_calculation() {
7972         // Test that we use the onion value `amt_to_forward` when
7973         // calculating whether we've reached the `total_msat` of an MPP
7974         // by having a routing node forward more than `amt_to_forward`
7975         // and checking that the receiving node doesn't generate
7976         // a PaymentClaimable event too early
7977         let node_count = 4;
7978         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7979         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7980         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7981         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7982
7983         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7984         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7985         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7986         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7987
7988         let total_msat = 100_000;
7989         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7990         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7991         let sample_path = route.paths.pop().unwrap();
7992
7993         let mut path_1 = sample_path.clone();
7994         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7995         path_1.hops[0].short_channel_id = chan_1_id;
7996         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7997         path_1.hops[1].short_channel_id = chan_3_id;
7998         path_1.hops[1].fee_msat = 100_000;
7999         route.paths.push(path_1);
8000
8001         let mut path_2 = sample_path.clone();
8002         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8003         path_2.hops[0].short_channel_id = chan_2_id;
8004         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8005         path_2.hops[1].short_channel_id = chan_4_id;
8006         path_2.hops[1].fee_msat = 1_000;
8007         route.paths.push(path_2);
8008
8009         // Send payment
8010         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8011         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8012                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8013         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8014                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8015         check_added_monitors!(nodes[0], expected_paths.len());
8016
8017         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8018         assert_eq!(events.len(), expected_paths.len());
8019
8020         // First path
8021         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8022         let mut payment_event = SendEvent::from_event(ev);
8023         let mut prev_node = &nodes[0];
8024
8025         for (idx, &node) in expected_paths[0].iter().enumerate() {
8026                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8027
8028                 if idx == 0 { // routing node
8029                         let session_priv = [3; 32];
8030                         let height = nodes[0].best_block_info().1;
8031                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8032                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8033                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8034                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8035                         // Edit amt_to_forward to simulate the sender having set
8036                         // the final amount and the routing node taking less fee
8037                         onion_payloads[1].amt_to_forward = 99_000;
8038                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8039                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8040                 }
8041
8042                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8043                 check_added_monitors!(node, 0);
8044                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8045                 expect_pending_htlcs_forwardable!(node);
8046
8047                 if idx == 0 {
8048                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8049                         assert_eq!(events_2.len(), 1);
8050                         check_added_monitors!(node, 1);
8051                         payment_event = SendEvent::from_event(events_2.remove(0));
8052                         assert_eq!(payment_event.msgs.len(), 1);
8053                 } else {
8054                         let events_2 = node.node.get_and_clear_pending_events();
8055                         assert!(events_2.is_empty());
8056                 }
8057
8058                 prev_node = node;
8059         }
8060
8061         // Second path
8062         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8063         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8064
8065         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8066 }
8067
8068 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8069
8070         let routing_node_count = msat_amounts.len();
8071         let node_count = routing_node_count + 2;
8072
8073         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8074         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8075         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8076         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8077
8078         let src_idx = 0;
8079         let dst_idx = 1;
8080
8081         // Create channels for each amount
8082         let mut expected_paths = Vec::with_capacity(routing_node_count);
8083         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8084         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8085         for i in 0..routing_node_count {
8086                 let routing_node = 2 + i;
8087                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8088                 src_chan_ids.push(src_chan_id);
8089                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8090                 dst_chan_ids.push(dst_chan_id);
8091                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8092                 expected_paths.push(path);
8093         }
8094         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8095
8096         // Create a route for each amount
8097         let example_amount = 100000;
8098         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);
8099         let sample_path = route.paths.pop().unwrap();
8100         for i in 0..routing_node_count {
8101                 let routing_node = 2 + i;
8102                 let mut path = sample_path.clone();
8103                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8104                 path.hops[0].short_channel_id = src_chan_ids[i];
8105                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8106                 path.hops[1].short_channel_id = dst_chan_ids[i];
8107                 path.hops[1].fee_msat = msat_amounts[i];
8108                 route.paths.push(path);
8109         }
8110
8111         // Send payment with manually set total_msat
8112         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8113         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8114                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8115         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8116                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8117         check_added_monitors!(nodes[src_idx], expected_paths.len());
8118
8119         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8120         assert_eq!(events.len(), expected_paths.len());
8121         let mut amount_received = 0;
8122         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8123                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8124
8125                 let current_path_amount = msat_amounts[path_idx];
8126                 amount_received += current_path_amount;
8127                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8128                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8129         }
8130
8131         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8132 }
8133
8134 #[test]
8135 fn test_overshoot_mpp() {
8136         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8137         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8138 }
8139
8140 #[test]
8141 fn test_simple_mpp() {
8142         // Simple test of sending a multi-path payment.
8143         let chanmon_cfgs = create_chanmon_cfgs(4);
8144         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8145         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8146         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8147
8148         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8149         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8150         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8151         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8152
8153         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8154         let path = route.paths[0].clone();
8155         route.paths.push(path);
8156         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8157         route.paths[0].hops[0].short_channel_id = chan_1_id;
8158         route.paths[0].hops[1].short_channel_id = chan_3_id;
8159         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8160         route.paths[1].hops[0].short_channel_id = chan_2_id;
8161         route.paths[1].hops[1].short_channel_id = chan_4_id;
8162         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8163         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8164 }
8165
8166 #[test]
8167 fn test_preimage_storage() {
8168         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8169         let chanmon_cfgs = create_chanmon_cfgs(2);
8170         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8172         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8173
8174         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8175
8176         {
8177                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8178                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8179                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8180                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8181                 check_added_monitors!(nodes[0], 1);
8182                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8183                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8184                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8185                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8186         }
8187         // Note that after leaving the above scope we have no knowledge of any arguments or return
8188         // values from previous calls.
8189         expect_pending_htlcs_forwardable!(nodes[1]);
8190         let events = nodes[1].node.get_and_clear_pending_events();
8191         assert_eq!(events.len(), 1);
8192         match events[0] {
8193                 Event::PaymentClaimable { ref purpose, .. } => {
8194                         match &purpose {
8195                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8196                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8197                                 },
8198                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8199                         }
8200                 },
8201                 _ => panic!("Unexpected event"),
8202         }
8203 }
8204
8205 #[test]
8206 #[allow(deprecated)]
8207 fn test_secret_timeout() {
8208         // Simple test of payment secret storage time outs. After
8209         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8210         let chanmon_cfgs = create_chanmon_cfgs(2);
8211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8213         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8214
8215         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8216
8217         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8218
8219         // We should fail to register the same payment hash twice, at least until we've connected a
8220         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8221         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8222                 assert_eq!(err, "Duplicate payment hash");
8223         } else { panic!(); }
8224         let mut block = {
8225                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8226                 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8227         };
8228         connect_block(&nodes[1], &block);
8229         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8230                 assert_eq!(err, "Duplicate payment hash");
8231         } else { panic!(); }
8232
8233         // If we then connect the second block, we should be able to register the same payment hash
8234         // again (this time getting a new payment secret).
8235         block.header.prev_blockhash = block.header.block_hash();
8236         block.header.time += 1;
8237         connect_block(&nodes[1], &block);
8238         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8239         assert_ne!(payment_secret_1, our_payment_secret);
8240
8241         {
8242                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8243                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8244                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8245                 check_added_monitors!(nodes[0], 1);
8246                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8247                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8248                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8249                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8250         }
8251         // Note that after leaving the above scope we have no knowledge of any arguments or return
8252         // values from previous calls.
8253         expect_pending_htlcs_forwardable!(nodes[1]);
8254         let events = nodes[1].node.get_and_clear_pending_events();
8255         assert_eq!(events.len(), 1);
8256         match events[0] {
8257                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8258                         assert!(payment_preimage.is_none());
8259                         assert_eq!(payment_secret, our_payment_secret);
8260                         // We don't actually have the payment preimage with which to claim this payment!
8261                 },
8262                 _ => panic!("Unexpected event"),
8263         }
8264 }
8265
8266 #[test]
8267 fn test_bad_secret_hash() {
8268         // Simple test of unregistered payment hash/invalid payment secret handling
8269         let chanmon_cfgs = create_chanmon_cfgs(2);
8270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8272         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8273
8274         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8275
8276         let random_payment_hash = PaymentHash([42; 32]);
8277         let random_payment_secret = PaymentSecret([43; 32]);
8278         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8279         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8280
8281         // All the below cases should end up being handled exactly identically, so we macro the
8282         // resulting events.
8283         macro_rules! handle_unknown_invalid_payment_data {
8284                 ($payment_hash: expr) => {
8285                         check_added_monitors!(nodes[0], 1);
8286                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8287                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8288                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8289                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8290
8291                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8292                         // again to process the pending backwards-failure of the HTLC
8293                         expect_pending_htlcs_forwardable!(nodes[1]);
8294                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8295                         check_added_monitors!(nodes[1], 1);
8296
8297                         // We should fail the payment back
8298                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8299                         match events.pop().unwrap() {
8300                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8301                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8302                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8303                                 },
8304                                 _ => panic!("Unexpected event"),
8305                         }
8306                 }
8307         }
8308
8309         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8310         // Error data is the HTLC value (100,000) and current block height
8311         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8312
8313         // Send a payment with the right payment hash but the wrong payment secret
8314         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8315                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8316         handle_unknown_invalid_payment_data!(our_payment_hash);
8317         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8318
8319         // Send a payment with a random payment hash, but the right payment secret
8320         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8321                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8322         handle_unknown_invalid_payment_data!(random_payment_hash);
8323         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8324
8325         // Send a payment with a random payment hash and random payment secret
8326         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8327                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8328         handle_unknown_invalid_payment_data!(random_payment_hash);
8329         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8330 }
8331
8332 #[test]
8333 fn test_update_err_monitor_lockdown() {
8334         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8335         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8336         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8337         // error.
8338         //
8339         // This scenario may happen in a watchtower setup, where watchtower process a block height
8340         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8341         // commitment at same time.
8342
8343         let chanmon_cfgs = create_chanmon_cfgs(2);
8344         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8345         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8346         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8347
8348         // Create some initial channel
8349         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8350         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8351
8352         // Rebalance the network to generate htlc in the two directions
8353         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8354
8355         // Route a HTLC from node 0 to node 1 (but don't settle)
8356         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8357
8358         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8359         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8360         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8361         let persister = test_utils::TestPersister::new();
8362         let watchtower = {
8363                 let new_monitor = {
8364                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8365                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8366                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8367                         assert!(new_monitor == *monitor);
8368                         new_monitor
8369                 };
8370                 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);
8371                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8372                 watchtower
8373         };
8374         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8375         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8376         // transaction lock time requirements here.
8377         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8378         watchtower.chain_monitor.block_connected(&block, 200);
8379
8380         // Try to update ChannelMonitor
8381         nodes[1].node.claim_funds(preimage);
8382         check_added_monitors!(nodes[1], 1);
8383         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8384
8385         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8386         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8387         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8388         {
8389                 let mut node_0_per_peer_lock;
8390                 let mut node_0_peer_state_lock;
8391                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8392                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8393                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8394                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8395                 } else { assert!(false); }
8396         }
8397         // Our local monitor is in-sync and hasn't processed yet timeout
8398         check_added_monitors!(nodes[0], 1);
8399         let events = nodes[0].node.get_and_clear_pending_events();
8400         assert_eq!(events.len(), 1);
8401 }
8402
8403 #[test]
8404 fn test_concurrent_monitor_claim() {
8405         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8406         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8407         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8408         // state N+1 confirms. Alice claims output from state N+1.
8409
8410         let chanmon_cfgs = create_chanmon_cfgs(2);
8411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8413         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8414
8415         // Create some initial channel
8416         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8417         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8418
8419         // Rebalance the network to generate htlc in the two directions
8420         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8421
8422         // Route a HTLC from node 0 to node 1 (but don't settle)
8423         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8424
8425         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8426         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8427         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8428         let persister = test_utils::TestPersister::new();
8429         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8430                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8431         );
8432         let watchtower_alice = {
8433                 let new_monitor = {
8434                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8435                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8436                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8437                         assert!(new_monitor == *monitor);
8438                         new_monitor
8439                 };
8440                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8441                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8442                 watchtower
8443         };
8444         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8445         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8446         // requirements here.
8447         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8448         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8449         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8450
8451         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8452         let alice_state = {
8453                 let mut txn = alice_broadcaster.txn_broadcast();
8454                 assert_eq!(txn.len(), 2);
8455                 txn.remove(0)
8456         };
8457
8458         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8459         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8460         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8461         let persister = test_utils::TestPersister::new();
8462         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8463         let watchtower_bob = {
8464                 let new_monitor = {
8465                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8466                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8467                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8468                         assert!(new_monitor == *monitor);
8469                         new_monitor
8470                 };
8471                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8472                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8473                 watchtower
8474         };
8475         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8476
8477         // Route another payment to generate another update with still previous HTLC pending
8478         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8479         nodes[1].node.send_payment_with_route(&route, payment_hash,
8480                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8481         check_added_monitors!(nodes[1], 1);
8482
8483         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8484         assert_eq!(updates.update_add_htlcs.len(), 1);
8485         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8486         {
8487                 let mut node_0_per_peer_lock;
8488                 let mut node_0_peer_state_lock;
8489                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8490                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8491                         // Watchtower Alice should already have seen the block and reject the update
8492                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8493                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8494                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8495                 } else { assert!(false); }
8496         }
8497         // Our local monitor is in-sync and hasn't processed yet timeout
8498         check_added_monitors!(nodes[0], 1);
8499
8500         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8501         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8502
8503         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8504         let bob_state_y;
8505         {
8506                 let mut txn = bob_broadcaster.txn_broadcast();
8507                 assert_eq!(txn.len(), 2);
8508                 bob_state_y = txn.remove(0);
8509         };
8510
8511         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8512         let height = HTLC_TIMEOUT_BROADCAST + 1;
8513         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8514         check_closed_broadcast(&nodes[0], 1, true);
8515         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8516         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8517         check_added_monitors(&nodes[0], 1);
8518         {
8519                 let htlc_txn = alice_broadcaster.txn_broadcast();
8520                 assert_eq!(htlc_txn.len(), 2);
8521                 check_spends!(htlc_txn[0], bob_state_y);
8522                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8523                 // it. However, she should, because it now has an invalid parent.
8524                 check_spends!(htlc_txn[1], alice_state);
8525         }
8526 }
8527
8528 #[test]
8529 fn test_pre_lockin_no_chan_closed_update() {
8530         // Test that if a peer closes a channel in response to a funding_created message we don't
8531         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8532         // message).
8533         //
8534         // Doing so would imply a channel monitor update before the initial channel monitor
8535         // registration, violating our API guarantees.
8536         //
8537         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8538         // then opening a second channel with the same funding output as the first (which is not
8539         // rejected because the first channel does not exist in the ChannelManager) and closing it
8540         // before receiving funding_signed.
8541         let chanmon_cfgs = create_chanmon_cfgs(2);
8542         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8543         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8544         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8545
8546         // Create an initial channel
8547         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8548         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8549         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8550         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8551         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8552
8553         // Move the first channel through the funding flow...
8554         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8555
8556         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8557         check_added_monitors!(nodes[0], 0);
8558
8559         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8560         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8561         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8562         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8563         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8564 }
8565
8566 #[test]
8567 fn test_htlc_no_detection() {
8568         // This test is a mutation to underscore the detection logic bug we had
8569         // before #653. HTLC value routed is above the remaining balance, thus
8570         // inverting HTLC and `to_remote` output. HTLC will come second and
8571         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8572         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8573         // outputs order detection for correct spending children filtring.
8574
8575         let chanmon_cfgs = create_chanmon_cfgs(2);
8576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8579
8580         // Create some initial channels
8581         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8582
8583         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8584         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8585         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8586         assert_eq!(local_txn[0].input.len(), 1);
8587         assert_eq!(local_txn[0].output.len(), 3);
8588         check_spends!(local_txn[0], chan_1.3);
8589
8590         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8591         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8592         connect_block(&nodes[0], &block);
8593         // We deliberately connect the local tx twice as this should provoke a failure calling
8594         // this test before #653 fix.
8595         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8596         check_closed_broadcast!(nodes[0], true);
8597         check_added_monitors!(nodes[0], 1);
8598         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8599         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8600
8601         let htlc_timeout = {
8602                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8603                 assert_eq!(node_txn.len(), 1);
8604                 assert_eq!(node_txn[0].input.len(), 1);
8605                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8606                 check_spends!(node_txn[0], local_txn[0]);
8607                 node_txn[0].clone()
8608         };
8609
8610         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8611         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8612         expect_payment_failed!(nodes[0], our_payment_hash, false);
8613 }
8614
8615 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8616         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8617         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8618         // Carol, Alice would be the upstream node, and Carol the downstream.)
8619         //
8620         // Steps of the test:
8621         // 1) Alice sends a HTLC to Carol through Bob.
8622         // 2) Carol doesn't settle the HTLC.
8623         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8624         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8625         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8626         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8627         // 5) Carol release the preimage to Bob off-chain.
8628         // 6) Bob claims the offered output on the broadcasted commitment.
8629         let chanmon_cfgs = create_chanmon_cfgs(3);
8630         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8631         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8632         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8633
8634         // Create some initial channels
8635         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8636         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8637
8638         // Steps (1) and (2):
8639         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8640         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8641
8642         // Check that Alice's commitment transaction now contains an output for this HTLC.
8643         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8644         check_spends!(alice_txn[0], chan_ab.3);
8645         assert_eq!(alice_txn[0].output.len(), 2);
8646         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8647         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8648         assert_eq!(alice_txn.len(), 2);
8649
8650         // Steps (3) and (4):
8651         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8652         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8653         let mut force_closing_node = 0; // Alice force-closes
8654         let mut counterparty_node = 1; // Bob if Alice force-closes
8655
8656         // Bob force-closes
8657         if !broadcast_alice {
8658                 force_closing_node = 1;
8659                 counterparty_node = 0;
8660         }
8661         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8662         check_closed_broadcast!(nodes[force_closing_node], true);
8663         check_added_monitors!(nodes[force_closing_node], 1);
8664         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8665         if go_onchain_before_fulfill {
8666                 let txn_to_broadcast = match broadcast_alice {
8667                         true => alice_txn.clone(),
8668                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8669                 };
8670                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8671                 if broadcast_alice {
8672                         check_closed_broadcast!(nodes[1], true);
8673                         check_added_monitors!(nodes[1], 1);
8674                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8675                 }
8676         }
8677
8678         // Step (5):
8679         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8680         // process of removing the HTLC from their commitment transactions.
8681         nodes[2].node.claim_funds(payment_preimage);
8682         check_added_monitors!(nodes[2], 1);
8683         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8684
8685         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8686         assert!(carol_updates.update_add_htlcs.is_empty());
8687         assert!(carol_updates.update_fail_htlcs.is_empty());
8688         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8689         assert!(carol_updates.update_fee.is_none());
8690         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8691
8692         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8693         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8694         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8695         if !go_onchain_before_fulfill && broadcast_alice {
8696                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8697                 assert_eq!(events.len(), 1);
8698                 match events[0] {
8699                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8700                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8701                         },
8702                         _ => panic!("Unexpected event"),
8703                 };
8704         }
8705         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8706         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8707         // Carol<->Bob's updated commitment transaction info.
8708         check_added_monitors!(nodes[1], 2);
8709
8710         let events = nodes[1].node.get_and_clear_pending_msg_events();
8711         assert_eq!(events.len(), 2);
8712         let bob_revocation = match events[0] {
8713                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8714                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8715                         (*msg).clone()
8716                 },
8717                 _ => panic!("Unexpected event"),
8718         };
8719         let bob_updates = match events[1] {
8720                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8721                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8722                         (*updates).clone()
8723                 },
8724                 _ => panic!("Unexpected event"),
8725         };
8726
8727         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8728         check_added_monitors!(nodes[2], 1);
8729         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8730         check_added_monitors!(nodes[2], 1);
8731
8732         let events = nodes[2].node.get_and_clear_pending_msg_events();
8733         assert_eq!(events.len(), 1);
8734         let carol_revocation = match events[0] {
8735                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8736                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8737                         (*msg).clone()
8738                 },
8739                 _ => panic!("Unexpected event"),
8740         };
8741         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8742         check_added_monitors!(nodes[1], 1);
8743
8744         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8745         // here's where we put said channel's commitment tx on-chain.
8746         let mut txn_to_broadcast = alice_txn.clone();
8747         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8748         if !go_onchain_before_fulfill {
8749                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8750                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8751                 if broadcast_alice {
8752                         check_closed_broadcast!(nodes[1], true);
8753                         check_added_monitors!(nodes[1], 1);
8754                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8755                 }
8756                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8757                 if broadcast_alice {
8758                         assert_eq!(bob_txn.len(), 1);
8759                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8760                 } else {
8761                         assert_eq!(bob_txn.len(), 2);
8762                         check_spends!(bob_txn[0], chan_ab.3);
8763                 }
8764         }
8765
8766         // Step (6):
8767         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8768         // broadcasted commitment transaction.
8769         {
8770                 let script_weight = match broadcast_alice {
8771                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8772                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8773                 };
8774                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8775                 // Bob force-closed and broadcasts the commitment transaction along with a
8776                 // HTLC-output-claiming transaction.
8777                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8778                 if broadcast_alice {
8779                         assert_eq!(bob_txn.len(), 1);
8780                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8781                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8782                 } else {
8783                         assert_eq!(bob_txn.len(), 2);
8784                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8785                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8786                 }
8787         }
8788 }
8789
8790 #[test]
8791 fn test_onchain_htlc_settlement_after_close() {
8792         do_test_onchain_htlc_settlement_after_close(true, true);
8793         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8794         do_test_onchain_htlc_settlement_after_close(true, false);
8795         do_test_onchain_htlc_settlement_after_close(false, false);
8796 }
8797
8798 #[test]
8799 fn test_duplicate_temporary_channel_id_from_different_peers() {
8800         // Tests that we can accept two different `OpenChannel` requests with the same
8801         // `temporary_channel_id`, as long as they are from different peers.
8802         let chanmon_cfgs = create_chanmon_cfgs(3);
8803         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8804         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8805         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8806
8807         // Create an first channel channel
8808         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8809         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8810
8811         // Create an second channel
8812         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8813         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8814
8815         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8816         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8817         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8818
8819         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8820         // `temporary_channel_id` as they are from different peers.
8821         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8822         {
8823                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8824                 assert_eq!(events.len(), 1);
8825                 match &events[0] {
8826                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8827                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8828                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8829                         },
8830                         _ => panic!("Unexpected event"),
8831                 }
8832         }
8833
8834         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8835         {
8836                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8837                 assert_eq!(events.len(), 1);
8838                 match &events[0] {
8839                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8840                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8841                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8842                         },
8843                         _ => panic!("Unexpected event"),
8844                 }
8845         }
8846 }
8847
8848 #[test]
8849 fn test_duplicate_chan_id() {
8850         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8851         // already open we reject it and keep the old channel.
8852         //
8853         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8854         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8855         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8856         // updating logic for the existing channel.
8857         let chanmon_cfgs = create_chanmon_cfgs(2);
8858         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8859         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8860         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8861
8862         // Create an initial channel
8863         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8864         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8865         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8866         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()));
8867
8868         // Try to create a second channel with the same temporary_channel_id as the first and check
8869         // that it is rejected.
8870         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8871         {
8872                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8873                 assert_eq!(events.len(), 1);
8874                 match events[0] {
8875                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8876                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8877                                 // first (valid) and second (invalid) channels are closed, given they both have
8878                                 // the same non-temporary channel_id. However, currently we do not, so we just
8879                                 // move forward with it.
8880                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8881                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8882                         },
8883                         _ => panic!("Unexpected event"),
8884                 }
8885         }
8886
8887         // Move the first channel through the funding flow...
8888         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8889
8890         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8891         check_added_monitors!(nodes[0], 0);
8892
8893         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8894         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8895         {
8896                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8897                 assert_eq!(added_monitors.len(), 1);
8898                 assert_eq!(added_monitors[0].0, funding_output);
8899                 added_monitors.clear();
8900         }
8901         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8902
8903         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8904
8905         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8906         let channel_id = funding_outpoint.to_channel_id();
8907
8908         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8909         // temporary one).
8910
8911         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8912         // Technically this is allowed by the spec, but we don't support it and there's little reason
8913         // to. Still, it shouldn't cause any other issues.
8914         open_chan_msg.temporary_channel_id = channel_id;
8915         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8916         {
8917                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8918                 assert_eq!(events.len(), 1);
8919                 match events[0] {
8920                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8921                                 // Technically, at this point, nodes[1] would be justified in thinking both
8922                                 // channels are closed, but currently we do not, so we just move forward with it.
8923                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8924                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8925                         },
8926                         _ => panic!("Unexpected event"),
8927                 }
8928         }
8929
8930         // Now try to create a second channel which has a duplicate funding output.
8931         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8932         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8933         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8934         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()));
8935         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8936
8937         let (_, funding_created) = {
8938                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8939                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8940                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8941                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8942                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8943                 // channelmanager in a possibly nonsense state instead).
8944                 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8945                 let logger = test_utils::TestLogger::new();
8946                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8947         };
8948         check_added_monitors!(nodes[0], 0);
8949         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8950         // At this point we'll look up if the channel_id is present and immediately fail the channel
8951         // without trying to persist the `ChannelMonitor`.
8952         check_added_monitors!(nodes[1], 0);
8953
8954         // ...still, nodes[1] will reject the duplicate channel.
8955         {
8956                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8957                 assert_eq!(events.len(), 1);
8958                 match events[0] {
8959                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8960                                 // Technically, at this point, nodes[1] would be justified in thinking both
8961                                 // channels are closed, but currently we do not, so we just move forward with it.
8962                                 assert_eq!(msg.channel_id, channel_id);
8963                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8964                         },
8965                         _ => panic!("Unexpected event"),
8966                 }
8967         }
8968
8969         // finally, finish creating the original channel and send a payment over it to make sure
8970         // everything is functional.
8971         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8972         {
8973                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8974                 assert_eq!(added_monitors.len(), 1);
8975                 assert_eq!(added_monitors[0].0, funding_output);
8976                 added_monitors.clear();
8977         }
8978         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8979
8980         let events_4 = nodes[0].node.get_and_clear_pending_events();
8981         assert_eq!(events_4.len(), 0);
8982         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8983         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8984
8985         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8986         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8987         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8988
8989         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8990 }
8991
8992 #[test]
8993 fn test_error_chans_closed() {
8994         // Test that we properly handle error messages, closing appropriate channels.
8995         //
8996         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8997         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8998         // we can test various edge cases around it to ensure we don't regress.
8999         let chanmon_cfgs = create_chanmon_cfgs(3);
9000         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9001         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9002         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9003
9004         // Create some initial channels
9005         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9006         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9007         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9008
9009         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9010         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9011         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9012
9013         // Closing a channel from a different peer has no effect
9014         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9015         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9016
9017         // Closing one channel doesn't impact others
9018         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9019         check_added_monitors!(nodes[0], 1);
9020         check_closed_broadcast!(nodes[0], false);
9021         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9022         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9023         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9024         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);
9025         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);
9026
9027         // A null channel ID should close all channels
9028         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9029         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9030         check_added_monitors!(nodes[0], 2);
9031         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9032         let events = nodes[0].node.get_and_clear_pending_msg_events();
9033         assert_eq!(events.len(), 2);
9034         match events[0] {
9035                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9036                         assert_eq!(msg.contents.flags & 2, 2);
9037                 },
9038                 _ => panic!("Unexpected event"),
9039         }
9040         match events[1] {
9041                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9042                         assert_eq!(msg.contents.flags & 2, 2);
9043                 },
9044                 _ => panic!("Unexpected event"),
9045         }
9046         // Note that at this point users of a standard PeerHandler will end up calling
9047         // peer_disconnected.
9048         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9049         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9050
9051         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9052         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9053         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9054 }
9055
9056 #[test]
9057 fn test_invalid_funding_tx() {
9058         // Test that we properly handle invalid funding transactions sent to us from a peer.
9059         //
9060         // Previously, all other major lightning implementations had failed to properly sanitize
9061         // funding transactions from their counterparties, leading to a multi-implementation critical
9062         // security vulnerability (though we always sanitized properly, we've previously had
9063         // un-released crashes in the sanitization process).
9064         //
9065         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9066         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9067         // gave up on it. We test this here by generating such a transaction.
9068         let chanmon_cfgs = create_chanmon_cfgs(2);
9069         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9070         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9071         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9072
9073         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9074         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()));
9075         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()));
9076
9077         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9078
9079         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9080         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9081         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9082         // its length.
9083         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9084         let wit_program_script: Script = wit_program.into();
9085         for output in tx.output.iter_mut() {
9086                 // Make the confirmed funding transaction have a bogus script_pubkey
9087                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9088         }
9089
9090         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9091         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()));
9092         check_added_monitors!(nodes[1], 1);
9093         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9094
9095         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()));
9096         check_added_monitors!(nodes[0], 1);
9097         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9098
9099         let events_1 = nodes[0].node.get_and_clear_pending_events();
9100         assert_eq!(events_1.len(), 0);
9101
9102         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9103         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9104         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9105
9106         let expected_err = "funding tx had wrong script/value or output index";
9107         confirm_transaction_at(&nodes[1], &tx, 1);
9108         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9109         check_added_monitors!(nodes[1], 1);
9110         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9111         assert_eq!(events_2.len(), 1);
9112         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9113                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9114                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9115                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9116                 } else { panic!(); }
9117         } else { panic!(); }
9118         assert_eq!(nodes[1].node.list_channels().len(), 0);
9119
9120         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9121         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9122         // as its not 32 bytes long.
9123         let mut spend_tx = Transaction {
9124                 version: 2i32, lock_time: PackedLockTime::ZERO,
9125                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9126                         previous_output: BitcoinOutPoint {
9127                                 txid: tx.txid(),
9128                                 vout: idx as u32,
9129                         },
9130                         script_sig: Script::new(),
9131                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9132                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9133                 }).collect(),
9134                 output: vec![TxOut {
9135                         value: 1000,
9136                         script_pubkey: Script::new(),
9137                 }]
9138         };
9139         check_spends!(spend_tx, tx);
9140         mine_transaction(&nodes[1], &spend_tx);
9141 }
9142
9143 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9144         // In the first version of the chain::Confirm interface, after a refactor was made to not
9145         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9146         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9147         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9148         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9149         // spending transaction until height N+1 (or greater). This was due to the way
9150         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9151         // spending transaction at the height the input transaction was confirmed at, not whether we
9152         // should broadcast a spending transaction at the current height.
9153         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9154         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9155         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9156         // until we learned about an additional block.
9157         //
9158         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9159         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9160         let chanmon_cfgs = create_chanmon_cfgs(3);
9161         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9162         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9163         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9164         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9165
9166         create_announced_chan_between_nodes(&nodes, 0, 1);
9167         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9168         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9169         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9170         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9171
9172         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9173         check_closed_broadcast!(nodes[1], true);
9174         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9175         check_added_monitors!(nodes[1], 1);
9176         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9177         assert_eq!(node_txn.len(), 1);
9178
9179         let conf_height = nodes[1].best_block_info().1;
9180         if !test_height_before_timelock {
9181                 connect_blocks(&nodes[1], 24 * 6);
9182         }
9183         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9184                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9185         if test_height_before_timelock {
9186                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9187                 // generate any events or broadcast any transactions
9188                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9189                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9190         } else {
9191                 // We should broadcast an HTLC transaction spending our funding transaction first
9192                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9193                 assert_eq!(spending_txn.len(), 2);
9194                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9195                 check_spends!(spending_txn[1], node_txn[0]);
9196                 // We should also generate a SpendableOutputs event with the to_self output (as its
9197                 // timelock is up).
9198                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9199                 assert_eq!(descriptor_spend_txn.len(), 1);
9200
9201                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9202                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9203                 // additional block built on top of the current chain.
9204                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9205                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9206                 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 }]);
9207                 check_added_monitors!(nodes[1], 1);
9208
9209                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9210                 assert!(updates.update_add_htlcs.is_empty());
9211                 assert!(updates.update_fulfill_htlcs.is_empty());
9212                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9213                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9214                 assert!(updates.update_fee.is_none());
9215                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9216                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9217                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9218         }
9219 }
9220
9221 #[test]
9222 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9223         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9224         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9225 }
9226
9227 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9228         let chanmon_cfgs = create_chanmon_cfgs(2);
9229         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9230         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9231         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9232
9233         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9234
9235         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9236                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9237         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9238
9239         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9240
9241         {
9242                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9243                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9244                 check_added_monitors!(nodes[0], 1);
9245                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9246                 assert_eq!(events.len(), 1);
9247                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9248                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9249                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9250         }
9251         expect_pending_htlcs_forwardable!(nodes[1]);
9252         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9253
9254         {
9255                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9256                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9257                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9258                 check_added_monitors!(nodes[0], 1);
9259                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9260                 assert_eq!(events.len(), 1);
9261                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9262                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9263                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9264                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9265                 // assume the second is a privacy attack (no longer particularly relevant
9266                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9267                 // the first HTLC delivered above.
9268         }
9269
9270         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9271         nodes[1].node.process_pending_htlc_forwards();
9272
9273         if test_for_second_fail_panic {
9274                 // Now we go fail back the first HTLC from the user end.
9275                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9276
9277                 let expected_destinations = vec![
9278                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9279                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9280                 ];
9281                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9282                 nodes[1].node.process_pending_htlc_forwards();
9283
9284                 check_added_monitors!(nodes[1], 1);
9285                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9286                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9287
9288                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9289                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9290                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9291
9292                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9293                 assert_eq!(failure_events.len(), 4);
9294                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9295                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9296                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9297                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9298         } else {
9299                 // Let the second HTLC fail and claim the first
9300                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9301                 nodes[1].node.process_pending_htlc_forwards();
9302
9303                 check_added_monitors!(nodes[1], 1);
9304                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9305                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9306                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9307
9308                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9309
9310                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9311         }
9312 }
9313
9314 #[test]
9315 fn test_dup_htlc_second_fail_panic() {
9316         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9317         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9318         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9319         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9320         do_test_dup_htlc_second_rejected(true);
9321 }
9322
9323 #[test]
9324 fn test_dup_htlc_second_rejected() {
9325         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9326         // simply reject the second HTLC but are still able to claim the first HTLC.
9327         do_test_dup_htlc_second_rejected(false);
9328 }
9329
9330 #[test]
9331 fn test_inconsistent_mpp_params() {
9332         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9333         // such HTLC and allow the second to stay.
9334         let chanmon_cfgs = create_chanmon_cfgs(4);
9335         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9336         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9337         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9338
9339         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9340         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9341         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9342         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9343
9344         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9345                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9346         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9347         assert_eq!(route.paths.len(), 2);
9348         route.paths.sort_by(|path_a, _| {
9349                 // Sort the path so that the path through nodes[1] comes first
9350                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9351                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9352         });
9353
9354         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9355
9356         let cur_height = nodes[0].best_block_info().1;
9357         let payment_id = PaymentId([42; 32]);
9358
9359         let session_privs = {
9360                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9361                 // ultimately have, just not right away.
9362                 let mut dup_route = route.clone();
9363                 dup_route.paths.push(route.paths[1].clone());
9364                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9365                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9366         };
9367         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9368                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9369                 &None, session_privs[0]).unwrap();
9370         check_added_monitors!(nodes[0], 1);
9371
9372         {
9373                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9374                 assert_eq!(events.len(), 1);
9375                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9376         }
9377         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9378
9379         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9380                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9381         check_added_monitors!(nodes[0], 1);
9382
9383         {
9384                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9385                 assert_eq!(events.len(), 1);
9386                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9387
9388                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9389                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9390
9391                 expect_pending_htlcs_forwardable!(nodes[2]);
9392                 check_added_monitors!(nodes[2], 1);
9393
9394                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9395                 assert_eq!(events.len(), 1);
9396                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9397
9398                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9399                 check_added_monitors!(nodes[3], 0);
9400                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9401
9402                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9403                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9404                 // post-payment_secrets) and fail back the new HTLC.
9405         }
9406         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9407         nodes[3].node.process_pending_htlc_forwards();
9408         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9409         nodes[3].node.process_pending_htlc_forwards();
9410
9411         check_added_monitors!(nodes[3], 1);
9412
9413         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9414         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9415         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9416
9417         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 }]);
9418         check_added_monitors!(nodes[2], 1);
9419
9420         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9421         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9422         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9423
9424         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9425
9426         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9427                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9428                 &None, session_privs[2]).unwrap();
9429         check_added_monitors!(nodes[0], 1);
9430
9431         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9432         assert_eq!(events.len(), 1);
9433         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9434
9435         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9436         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9437 }
9438
9439 #[test]
9440 fn test_keysend_payments_to_public_node() {
9441         let chanmon_cfgs = create_chanmon_cfgs(2);
9442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9445
9446         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9447         let network_graph = nodes[0].network_graph.clone();
9448         let payer_pubkey = nodes[0].node.get_our_node_id();
9449         let payee_pubkey = nodes[1].node.get_our_node_id();
9450         let route_params = RouteParameters {
9451                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9452                 final_value_msat: 10000,
9453         };
9454         let scorer = test_utils::TestScorer::new();
9455         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9456         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9457
9458         let test_preimage = PaymentPreimage([42; 32]);
9459         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9460                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9461         check_added_monitors!(nodes[0], 1);
9462         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9463         assert_eq!(events.len(), 1);
9464         let event = events.pop().unwrap();
9465         let path = vec![&nodes[1]];
9466         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9467         claim_payment(&nodes[0], &path, test_preimage);
9468 }
9469
9470 #[test]
9471 fn test_keysend_payments_to_private_node() {
9472         let chanmon_cfgs = create_chanmon_cfgs(2);
9473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9476
9477         let payer_pubkey = nodes[0].node.get_our_node_id();
9478         let payee_pubkey = nodes[1].node.get_our_node_id();
9479
9480         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9481         let route_params = RouteParameters {
9482                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9483                 final_value_msat: 10000,
9484         };
9485         let network_graph = nodes[0].network_graph.clone();
9486         let first_hops = nodes[0].node.list_usable_channels();
9487         let scorer = test_utils::TestScorer::new();
9488         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9489         let route = find_route(
9490                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9491                 nodes[0].logger, &scorer, &(), &random_seed_bytes
9492         ).unwrap();
9493
9494         let test_preimage = PaymentPreimage([42; 32]);
9495         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9496                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9497         check_added_monitors!(nodes[0], 1);
9498         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9499         assert_eq!(events.len(), 1);
9500         let event = events.pop().unwrap();
9501         let path = vec![&nodes[1]];
9502         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9503         claim_payment(&nodes[0], &path, test_preimage);
9504 }
9505
9506 #[test]
9507 fn test_double_partial_claim() {
9508         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9509         // time out, the sender resends only some of the MPP parts, then the user processes the
9510         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9511         // amount.
9512         let chanmon_cfgs = create_chanmon_cfgs(4);
9513         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9514         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9515         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9516
9517         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9518         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9519         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9520         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9521
9522         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9523         assert_eq!(route.paths.len(), 2);
9524         route.paths.sort_by(|path_a, _| {
9525                 // Sort the path so that the path through nodes[1] comes first
9526                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9527                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9528         });
9529
9530         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9531         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9532         // amount of time to respond to.
9533
9534         // Connect some blocks to time out the payment
9535         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9536         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9537
9538         let failed_destinations = vec![
9539                 HTLCDestination::FailedPayment { payment_hash },
9540                 HTLCDestination::FailedPayment { payment_hash },
9541         ];
9542         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9543
9544         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9545
9546         // nodes[1] now retries one of the two paths...
9547         nodes[0].node.send_payment_with_route(&route, payment_hash,
9548                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9549         check_added_monitors!(nodes[0], 2);
9550
9551         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9552         assert_eq!(events.len(), 2);
9553         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9554         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9555
9556         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9557         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9558         nodes[3].node.claim_funds(payment_preimage);
9559         check_added_monitors!(nodes[3], 0);
9560         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9561 }
9562
9563 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9564 #[derive(Clone, Copy, PartialEq)]
9565 enum ExposureEvent {
9566         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9567         AtHTLCForward,
9568         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9569         AtHTLCReception,
9570         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9571         AtUpdateFeeOutbound,
9572 }
9573
9574 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9575         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9576         // policy.
9577         //
9578         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9579         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9580         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9581         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9582         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9583         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9584         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9585         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9586
9587         let chanmon_cfgs = create_chanmon_cfgs(2);
9588         let mut config = test_default_channel_config();
9589         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9592         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9593
9594         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9595         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9596         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9597         open_channel.max_accepted_htlcs = 60;
9598         if on_holder_tx {
9599                 open_channel.dust_limit_satoshis = 546;
9600         }
9601         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9602         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9603         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9604
9605         let opt_anchors = false;
9606
9607         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9608
9609         if on_holder_tx {
9610                 let mut node_0_per_peer_lock;
9611                 let mut node_0_peer_state_lock;
9612                 let mut chan = get_outbound_v1_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9613                 chan.context.holder_dust_limit_satoshis = 546;
9614         }
9615
9616         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9617         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()));
9618         check_added_monitors!(nodes[1], 1);
9619         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9620
9621         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()));
9622         check_added_monitors!(nodes[0], 1);
9623         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9624
9625         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9626         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9627         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9628
9629         // Fetch a route in advance as we will be unable to once we're unable to send.
9630         let (mut route, payment_hash, _, payment_secret) =
9631                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9632
9633         let dust_buffer_feerate = {
9634                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9635                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9636                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9637                 chan.context.get_dust_buffer_feerate(None) as u64
9638         };
9639         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;
9640         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9641
9642         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;
9643         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9644
9645         let dust_htlc_on_counterparty_tx: u64 = 4;
9646         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9647
9648         if on_holder_tx {
9649                 if dust_outbound_balance {
9650                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9651                         // Outbound dust balance: 4372 sats
9652                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9653                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9654                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9655                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9656                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9657                         }
9658                 } else {
9659                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9660                         // Inbound dust balance: 4372 sats
9661                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9662                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9663                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9664                         }
9665                 }
9666         } else {
9667                 if dust_outbound_balance {
9668                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9669                         // Outbound dust balance: 5000 sats
9670                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9671                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9672                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9673                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9674                         }
9675                 } else {
9676                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9677                         // Inbound dust balance: 5000 sats
9678                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9679                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9680                         }
9681                 }
9682         }
9683
9684         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9685                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9686                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9687                 // With default dust exposure: 5000 sats
9688                 if on_holder_tx {
9689                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9690                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9691                                 ), true, APIError::ChannelUnavailable { .. }, {});
9692                 } else {
9693                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9694                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9695                                 ), true, APIError::ChannelUnavailable { .. }, {});
9696                 }
9697         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9698                 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 + 1 });
9699                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9700                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9701                 check_added_monitors!(nodes[1], 1);
9702                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9703                 assert_eq!(events.len(), 1);
9704                 let payment_event = SendEvent::from_event(events.remove(0));
9705                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9706                 // With default dust exposure: 5000 sats
9707                 if on_holder_tx {
9708                         // Outbound dust balance: 6399 sats
9709                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9710                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9711                         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);
9712                 } else {
9713                         // Outbound dust balance: 5200 sats
9714                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9715                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9716                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 1,
9717                                         config.channel_config.max_dust_htlc_exposure_msat), 1);
9718                 }
9719         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9720                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9721                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9722                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9723                 {
9724                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9725                         *feerate_lock = *feerate_lock * 10;
9726                 }
9727                 nodes[0].node.timer_tick_occurred();
9728                 check_added_monitors!(nodes[0], 1);
9729                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9730         }
9731
9732         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9733         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9734         added_monitors.clear();
9735 }
9736
9737 #[test]
9738 fn test_max_dust_htlc_exposure() {
9739         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9740         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9741         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9742         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9743         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9744         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9745         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9746         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9747         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9748         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9749         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9750         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9751 }
9752
9753 #[test]
9754 fn test_non_final_funding_tx() {
9755         let chanmon_cfgs = create_chanmon_cfgs(2);
9756         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9757         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9758         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9759
9760         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9761         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9762         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9763         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9764         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9765
9766         let best_height = nodes[0].node.best_block.read().unwrap().height();
9767
9768         let chan_id = *nodes[0].network_chan_count.borrow();
9769         let events = nodes[0].node.get_and_clear_pending_events();
9770         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9771         assert_eq!(events.len(), 1);
9772         let mut tx = match events[0] {
9773                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9774                         // Timelock the transaction _beyond_ the best client height + 1.
9775                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9776                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9777                         }]}
9778                 },
9779                 _ => panic!("Unexpected event"),
9780         };
9781         // Transaction should fail as it's evaluated as non-final for propagation.
9782         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9783                 Err(APIError::APIMisuseError { err }) => {
9784                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9785                 },
9786                 _ => panic!()
9787         }
9788
9789         // However, transaction should be accepted if it's in a +1 headroom from best block.
9790         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9791         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9792         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9793 }
9794
9795 #[test]
9796 fn accept_busted_but_better_fee() {
9797         // If a peer sends us a fee update that is too low, but higher than our previous channel
9798         // feerate, we should accept it. In the future we may want to consider closing the channel
9799         // later, but for now we only accept the update.
9800         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9804
9805         create_chan_between_nodes(&nodes[0], &nodes[1]);
9806
9807         // Set nodes[1] to expect 5,000 sat/kW.
9808         {
9809                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9810                 *feerate_lock = 5000;
9811         }
9812
9813         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9814         {
9815                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9816                 *feerate_lock = 1000;
9817         }
9818         nodes[0].node.timer_tick_occurred();
9819         check_added_monitors!(nodes[0], 1);
9820
9821         let events = nodes[0].node.get_and_clear_pending_msg_events();
9822         assert_eq!(events.len(), 1);
9823         match events[0] {
9824                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9825                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9826                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9827                 },
9828                 _ => panic!("Unexpected event"),
9829         };
9830
9831         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9832         // it.
9833         {
9834                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9835                 *feerate_lock = 2000;
9836         }
9837         nodes[0].node.timer_tick_occurred();
9838         check_added_monitors!(nodes[0], 1);
9839
9840         let events = nodes[0].node.get_and_clear_pending_msg_events();
9841         assert_eq!(events.len(), 1);
9842         match events[0] {
9843                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9844                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9845                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9846                 },
9847                 _ => panic!("Unexpected event"),
9848         };
9849
9850         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9851         // channel.
9852         {
9853                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9854                 *feerate_lock = 1000;
9855         }
9856         nodes[0].node.timer_tick_occurred();
9857         check_added_monitors!(nodes[0], 1);
9858
9859         let events = nodes[0].node.get_and_clear_pending_msg_events();
9860         assert_eq!(events.len(), 1);
9861         match events[0] {
9862                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9863                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9864                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9865                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9866                         check_closed_broadcast!(nodes[1], true);
9867                         check_added_monitors!(nodes[1], 1);
9868                 },
9869                 _ => panic!("Unexpected event"),
9870         };
9871 }
9872
9873 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9874         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9875         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9876         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9877         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9878         let min_final_cltv_expiry_delta = 120;
9879         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9880                 min_final_cltv_expiry_delta - 2 };
9881         let recv_value = 100_000;
9882
9883         create_chan_between_nodes(&nodes[0], &nodes[1]);
9884
9885         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9886         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9887                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9888                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9889                 (payment_hash, payment_preimage, payment_secret)
9890         } else {
9891                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9892                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9893         };
9894         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9895         nodes[0].node.send_payment_with_route(&route, payment_hash,
9896                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9897         check_added_monitors!(nodes[0], 1);
9898         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9899         assert_eq!(events.len(), 1);
9900         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9901         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9902         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9903         expect_pending_htlcs_forwardable!(nodes[1]);
9904
9905         if valid_delta {
9906                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9907                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9908
9909                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9910         } else {
9911                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9912
9913                 check_added_monitors!(nodes[1], 1);
9914
9915                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9916                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9917                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9918
9919                 expect_payment_failed!(nodes[0], payment_hash, true);
9920         }
9921 }
9922
9923 #[test]
9924 fn test_payment_with_custom_min_cltv_expiry_delta() {
9925         do_payment_with_custom_min_final_cltv_expiry(false, false);
9926         do_payment_with_custom_min_final_cltv_expiry(false, true);
9927         do_payment_with_custom_min_final_cltv_expiry(true, false);
9928         do_payment_with_custom_min_final_cltv_expiry(true, true);
9929 }
9930
9931 #[test]
9932 fn test_disconnects_peer_awaiting_response_ticks() {
9933         // Tests that nodes which are awaiting on a response critical for channel responsiveness
9934         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9935         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9936         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9937         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9938         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9939
9940         // Asserts a disconnect event is queued to the user.
9941         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9942                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9943                         if let MessageSendEvent::HandleError { action, .. } = event {
9944                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9945                                         Some(())
9946                                 } else {
9947                                         None
9948                                 }
9949                         } else {
9950                                 None
9951                         }
9952                 );
9953                 assert_eq!(disconnect_event.is_some(), should_disconnect);
9954         };
9955
9956         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9957         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9958         let check_disconnect = |node: &Node| {
9959                 // No disconnect without any timer ticks.
9960                 check_disconnect_event(node, false);
9961
9962                 // No disconnect with 1 timer tick less than required.
9963                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9964                         node.node.timer_tick_occurred();
9965                         check_disconnect_event(node, false);
9966                 }
9967
9968                 // Disconnect after reaching the required ticks.
9969                 node.node.timer_tick_occurred();
9970                 check_disconnect_event(node, true);
9971
9972                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9973                 node.node.timer_tick_occurred();
9974                 check_disconnect_event(node, true);
9975         };
9976
9977         create_chan_between_nodes(&nodes[0], &nodes[1]);
9978
9979         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9980         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9981         nodes[0].node.timer_tick_occurred();
9982         check_added_monitors!(&nodes[0], 1);
9983         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9984         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9985         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9986         check_added_monitors!(&nodes[1], 1);
9987
9988         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9989         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9990         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9991         check_added_monitors!(&nodes[0], 1);
9992         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9993         check_added_monitors(&nodes[0], 1);
9994
9995         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9996         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9997         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9998         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9999         check_disconnect(&nodes[1]);
10000
10001         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10002         //
10003         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10004         // final `RevokeAndACK` to Bob to complete it.
10005         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10006         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10007         let bob_init = msgs::Init {
10008                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10009         };
10010         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10011         let alice_init = msgs::Init {
10012                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10013         };
10014         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10015
10016         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10017         // received Bob's yet, so she should disconnect him after reaching
10018         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10019         let alice_channel_reestablish = get_event_msg!(
10020                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10021         );
10022         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10023         check_disconnect(&nodes[0]);
10024
10025         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10026         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10027                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10028                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10029                         Some(msg.clone())
10030                 } else {
10031                         None
10032                 }
10033         ).unwrap();
10034         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10035
10036         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10037         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10038                 nodes[0].node.timer_tick_occurred();
10039                 check_disconnect_event(&nodes[0], false);
10040         }
10041
10042         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10043         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10044         check_disconnect(&nodes[1]);
10045
10046         // Finally, have Bob process the last message.
10047         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10048         check_added_monitors(&nodes[1], 1);
10049
10050         // At this point, neither node should attempt to disconnect each other, since they aren't
10051         // waiting on any messages.
10052         for node in &nodes {
10053                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10054                         node.node.timer_tick_occurred();
10055                         check_disconnect_event(node, false);
10056                 }
10057         }
10058 }