271ff541a84981733090b30600956886c2845d40
[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, ChannelTypeFeatures, 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, MaxDustHTLCExposure};
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 channel_type_features = ChannelTypeFeatures::only_static_remote_key();
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 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, &channel_type_features));
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 channel_type_features = ChannelTypeFeatures::only_static_remote_key();
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(&channel_type_features) + 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(&channel_type_features)) 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, &channel_type_features) / 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, &channel_type_features) / 1000,
733                         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_channel_type_features!(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                 skimmed_fee_msat: None,
1397         };
1398
1399         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1400
1401         // Now manually create the commitment_signed message corresponding to the update_add
1402         // nodes[0] just sent. In the code for construction of this message, "local" refers
1403         // to the sender of the message, and "remote" refers to the receiver.
1404
1405         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1406
1407         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1408
1409         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1410         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1411         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1412                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1413                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1414                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1415                 let chan_signer = local_chan.get_signer();
1416                 // Make the signer believe we validated another commitment, so we can release the secret
1417                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1418
1419                 let pubkeys = chan_signer.pubkeys();
1420                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1421                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1422                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1423                  chan_signer.pubkeys().funding_pubkey)
1424         };
1425         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1426                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1427                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1428                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1429                 let chan_signer = remote_chan.get_signer();
1430                 let pubkeys = chan_signer.pubkeys();
1431                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1432                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1433                  chan_signer.pubkeys().funding_pubkey)
1434         };
1435
1436         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1437         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1438                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1439
1440         // Build the remote commitment transaction so we can sign it, and then later use the
1441         // signature for the commitment_signed message.
1442         let local_chan_balance = 1313;
1443
1444         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1445                 offered: false,
1446                 amount_msat: 3460001,
1447                 cltv_expiry: htlc_cltv,
1448                 payment_hash,
1449                 transaction_output_index: Some(1),
1450         };
1451
1452         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1453
1454         let res = {
1455                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1456                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1457                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1458                 let local_chan_signer = local_chan.get_signer();
1459                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1460                         commitment_number,
1461                         95000,
1462                         local_chan_balance,
1463                         local_funding, remote_funding,
1464                         commit_tx_keys.clone(),
1465                         feerate_per_kw,
1466                         &mut vec![(accepted_htlc_info, ())],
1467                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1468                 );
1469                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1470         };
1471
1472         let commit_signed_msg = msgs::CommitmentSigned {
1473                 channel_id: chan.2,
1474                 signature: res.0,
1475                 htlc_signatures: res.1,
1476                 #[cfg(taproot)]
1477                 partial_signature_with_nonce: None,
1478         };
1479
1480         // Send the commitment_signed message to the nodes[1].
1481         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1482         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1483
1484         // Send the RAA to nodes[1].
1485         let raa_msg = msgs::RevokeAndACK {
1486                 channel_id: chan.2,
1487                 per_commitment_secret: local_secret,
1488                 next_per_commitment_point: next_local_point,
1489                 #[cfg(taproot)]
1490                 next_local_nonce: None,
1491         };
1492         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1493
1494         let events = nodes[1].node.get_and_clear_pending_msg_events();
1495         assert_eq!(events.len(), 1);
1496         // Make sure the HTLC failed in the way we expect.
1497         match events[0] {
1498                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1499                         assert_eq!(update_fail_htlcs.len(), 1);
1500                         update_fail_htlcs[0].clone()
1501                 },
1502                 _ => panic!("Unexpected event"),
1503         };
1504         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1505                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1506
1507         check_added_monitors!(nodes[1], 2);
1508 }
1509
1510 #[test]
1511 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1512         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1513         // Set the fee rate for the channel very high, to the point where the fundee
1514         // sending any above-dust amount would result in a channel reserve violation.
1515         // In this test we check that we would be prevented from sending an HTLC in
1516         // this situation.
1517         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1520         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1521         let default_config = UserConfig::default();
1522         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1523
1524         let mut push_amt = 100_000_000;
1525         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1526
1527         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1528
1529         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1530
1531         // Fetch a route in advance as we will be unable to once we're unable to send.
1532         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1533         // Sending exactly enough to hit the reserve amount should be accepted
1534         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1535                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1536         }
1537
1538         // However one more HTLC should be significantly over the reserve amount and fail.
1539         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1540                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1541                 ), true, APIError::ChannelUnavailable { .. }, {});
1542         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1543 }
1544
1545 #[test]
1546 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1547         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1548         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1551         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1552         let default_config = UserConfig::default();
1553         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1554
1555         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1556         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1557         // transaction fee with 0 HTLCs (183 sats)).
1558         let mut push_amt = 100_000_000;
1559         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1560         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1561         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1562
1563         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1564         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1565                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1566         }
1567
1568         let (mut route, payment_hash, _, payment_secret) =
1569                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1570         route.paths[0].hops[0].fee_msat = 700_000;
1571         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1572         let secp_ctx = Secp256k1::new();
1573         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1574         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1575         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1576         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1577                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1578         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1579         let msg = msgs::UpdateAddHTLC {
1580                 channel_id: chan.2,
1581                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1582                 amount_msat: htlc_msat,
1583                 payment_hash: payment_hash,
1584                 cltv_expiry: htlc_cltv,
1585                 onion_routing_packet: onion_packet,
1586                 skimmed_fee_msat: None,
1587         };
1588
1589         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1590         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1591         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);
1592         assert_eq!(nodes[0].node.list_channels().len(), 0);
1593         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1594         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1595         check_added_monitors!(nodes[0], 1);
1596         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() });
1597 }
1598
1599 #[test]
1600 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1601         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1602         // calculating our commitment transaction fee (this was previously broken).
1603         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1604         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1605
1606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1608         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1609         let default_config = UserConfig::default();
1610         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1611
1612         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1613         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1614         // transaction fee with 0 HTLCs (183 sats)).
1615         let mut push_amt = 100_000_000;
1616         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1617         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1618         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1619
1620         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1621                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1622         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1623         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1624         // commitment transaction fee.
1625         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1626
1627         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1628         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1629                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1630         }
1631
1632         // One more than the dust amt should fail, however.
1633         let (mut route, our_payment_hash, _, our_payment_secret) =
1634                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1635         route.paths[0].hops[0].fee_msat += 1;
1636         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1637                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1638                 ), true, APIError::ChannelUnavailable { .. }, {});
1639 }
1640
1641 #[test]
1642 fn test_chan_init_feerate_unaffordability() {
1643         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1644         // channel reserve and feerate requirements.
1645         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1646         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1649         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1650         let default_config = UserConfig::default();
1651         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1652
1653         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1654         // HTLC.
1655         let mut push_amt = 100_000_000;
1656         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1657         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1658                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1659
1660         // During open, we don't have a "counterparty channel reserve" to check against, so that
1661         // requirement only comes into play on the open_channel handling side.
1662         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1663         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1664         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1665         open_channel_msg.push_msat += 1;
1666         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1667
1668         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1669         assert_eq!(msg_events.len(), 1);
1670         match msg_events[0] {
1671                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1672                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1673                 },
1674                 _ => panic!("Unexpected event"),
1675         }
1676 }
1677
1678 #[test]
1679 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1680         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1681         // calculating our counterparty's commitment transaction fee (this was previously broken).
1682         let chanmon_cfgs = create_chanmon_cfgs(2);
1683         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1684         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1685         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1686         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1687
1688         let payment_amt = 46000; // Dust amount
1689         // In the previous code, these first four payments would succeed.
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694
1695         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701
1702         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1703         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1704         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1705         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1706 }
1707
1708 #[test]
1709 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1710         let chanmon_cfgs = create_chanmon_cfgs(3);
1711         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1712         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1713         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1714         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1715         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1716
1717         let feemsat = 239;
1718         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1719         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1720         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1721         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1722
1723         // Add a 2* and +1 for the fee spike reserve.
1724         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1725         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;
1726         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1727
1728         // Add a pending HTLC.
1729         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1730         let payment_event_1 = {
1731                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1732                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1733                 check_added_monitors!(nodes[0], 1);
1734
1735                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1736                 assert_eq!(events.len(), 1);
1737                 SendEvent::from_event(events.remove(0))
1738         };
1739         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1740
1741         // Attempt to trigger a channel reserve violation --> payment failure.
1742         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1743         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;
1744         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1745         let mut route_2 = route_1.clone();
1746         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1747
1748         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1749         let secp_ctx = Secp256k1::new();
1750         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1751         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1752         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1753         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1754                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1755         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1756         let msg = msgs::UpdateAddHTLC {
1757                 channel_id: chan.2,
1758                 htlc_id: 1,
1759                 amount_msat: htlc_msat + 1,
1760                 payment_hash: our_payment_hash_1,
1761                 cltv_expiry: htlc_cltv,
1762                 onion_routing_packet: onion_packet,
1763                 skimmed_fee_msat: None,
1764         };
1765
1766         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1767         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1768         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1769         assert_eq!(nodes[1].node.list_channels().len(), 1);
1770         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1771         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1772         check_added_monitors!(nodes[1], 1);
1773         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1774 }
1775
1776 #[test]
1777 fn test_inbound_outbound_capacity_is_not_zero() {
1778         let chanmon_cfgs = create_chanmon_cfgs(2);
1779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1781         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1782         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1783         let channels0 = node_chanmgrs[0].list_channels();
1784         let channels1 = node_chanmgrs[1].list_channels();
1785         let default_config = UserConfig::default();
1786         assert_eq!(channels0.len(), 1);
1787         assert_eq!(channels1.len(), 1);
1788
1789         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1790         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1791         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1792
1793         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1794         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1795 }
1796
1797 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1798         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1799 }
1800
1801 #[test]
1802 fn test_channel_reserve_holding_cell_htlcs() {
1803         let chanmon_cfgs = create_chanmon_cfgs(3);
1804         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1805         // When this test was written, the default base fee floated based on the HTLC count.
1806         // It is now fixed, so we simply set the fee to the expected value here.
1807         let mut config = test_default_channel_config();
1808         config.channel_config.forwarding_fee_base_msat = 239;
1809         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1810         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1811         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1812         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1813
1814         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1815         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1816
1817         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1818         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1819
1820         macro_rules! expect_forward {
1821                 ($node: expr) => {{
1822                         let mut events = $node.node.get_and_clear_pending_msg_events();
1823                         assert_eq!(events.len(), 1);
1824                         check_added_monitors!($node, 1);
1825                         let payment_event = SendEvent::from_event(events.remove(0));
1826                         payment_event
1827                 }}
1828         }
1829
1830         let feemsat = 239; // set above
1831         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1832         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1833         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1834
1835         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1836
1837         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1838         {
1839                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1840                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1841                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1842                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1843                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1844
1845                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1846                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1847                         ), true, APIError::ChannelUnavailable { .. }, {});
1848                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1849         }
1850
1851         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1852         // nodes[0]'s wealth
1853         loop {
1854                 let amt_msat = recv_value_0 + total_fee_msat;
1855                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1856                 // Also, ensure that each payment has enough to be over the dust limit to
1857                 // ensure it'll be included in each commit tx fee calculation.
1858                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1859                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1860                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1861                         break;
1862                 }
1863
1864                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1865                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1866                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1867                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1868                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1869
1870                 let (stat01_, stat11_, stat12_, stat22_) = (
1871                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1872                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1873                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1874                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1875                 );
1876
1877                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1878                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1879                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1880                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1881                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1882         }
1883
1884         // adding pending output.
1885         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1886         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1887         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1888         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1889         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1890         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1891         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1892         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1893         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1894         // policy.
1895         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1896         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1897         let amt_msat_1 = recv_value_1 + total_fee_msat;
1898
1899         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);
1900         let payment_event_1 = {
1901                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1902                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1903                 check_added_monitors!(nodes[0], 1);
1904
1905                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1906                 assert_eq!(events.len(), 1);
1907                 SendEvent::from_event(events.remove(0))
1908         };
1909         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1910
1911         // channel reserve test with htlc pending output > 0
1912         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1913         {
1914                 let mut route = route_1.clone();
1915                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1916                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1917                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1918                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1919                         ), true, APIError::ChannelUnavailable { .. }, {});
1920                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1921         }
1922
1923         // split the rest to test holding cell
1924         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1925         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1926         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1927         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1928         {
1929                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1930                 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);
1931         }
1932
1933         // now see if they go through on both sides
1934         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);
1935         // but this will stuck in the holding cell
1936         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1937                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1938         check_added_monitors!(nodes[0], 0);
1939         let events = nodes[0].node.get_and_clear_pending_events();
1940         assert_eq!(events.len(), 0);
1941
1942         // test with outbound holding cell amount > 0
1943         {
1944                 let (mut route, our_payment_hash, _, our_payment_secret) =
1945                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1946                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1947                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1948                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1949                         ), true, APIError::ChannelUnavailable { .. }, {});
1950                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1951         }
1952
1953         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);
1954         // this will also stuck in the holding cell
1955         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1956                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1957         check_added_monitors!(nodes[0], 0);
1958         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1959         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1960
1961         // flush the pending htlc
1962         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1963         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1964         check_added_monitors!(nodes[1], 1);
1965
1966         // the pending htlc should be promoted to committed
1967         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1968         check_added_monitors!(nodes[0], 1);
1969         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1970
1971         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1972         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1973         // No commitment_signed so get_event_msg's assert(len == 1) passes
1974         check_added_monitors!(nodes[0], 1);
1975
1976         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1977         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1978         check_added_monitors!(nodes[1], 1);
1979
1980         expect_pending_htlcs_forwardable!(nodes[1]);
1981
1982         let ref payment_event_11 = expect_forward!(nodes[1]);
1983         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1984         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1985
1986         expect_pending_htlcs_forwardable!(nodes[2]);
1987         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1988
1989         // flush the htlcs in the holding cell
1990         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1991         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1992         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1993         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1994         expect_pending_htlcs_forwardable!(nodes[1]);
1995
1996         let ref payment_event_3 = expect_forward!(nodes[1]);
1997         assert_eq!(payment_event_3.msgs.len(), 2);
1998         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1999         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2000
2001         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2002         expect_pending_htlcs_forwardable!(nodes[2]);
2003
2004         let events = nodes[2].node.get_and_clear_pending_events();
2005         assert_eq!(events.len(), 2);
2006         match events[0] {
2007                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2008                         assert_eq!(our_payment_hash_21, *payment_hash);
2009                         assert_eq!(recv_value_21, amount_msat);
2010                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2011                         assert_eq!(via_channel_id, Some(chan_2.2));
2012                         match &purpose {
2013                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2014                                         assert!(payment_preimage.is_none());
2015                                         assert_eq!(our_payment_secret_21, *payment_secret);
2016                                 },
2017                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2018                         }
2019                 },
2020                 _ => panic!("Unexpected event"),
2021         }
2022         match events[1] {
2023                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2024                         assert_eq!(our_payment_hash_22, *payment_hash);
2025                         assert_eq!(recv_value_22, amount_msat);
2026                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2027                         assert_eq!(via_channel_id, Some(chan_2.2));
2028                         match &purpose {
2029                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2030                                         assert!(payment_preimage.is_none());
2031                                         assert_eq!(our_payment_secret_22, *payment_secret);
2032                                 },
2033                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2034                         }
2035                 },
2036                 _ => panic!("Unexpected event"),
2037         }
2038
2039         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2040         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2041         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2042
2043         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2044         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2045         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2046
2047         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2048         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);
2049         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2050         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2051         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2052
2053         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2054         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2055 }
2056
2057 #[test]
2058 fn channel_reserve_in_flight_removes() {
2059         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2060         // can send to its counterparty, but due to update ordering, the other side may not yet have
2061         // considered those HTLCs fully removed.
2062         // This tests that we don't count HTLCs which will not be included in the next remote
2063         // commitment transaction towards the reserve value (as it implies no commitment transaction
2064         // will be generated which violates the remote reserve value).
2065         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2066         // To test this we:
2067         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2068         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2069         //    you only consider the value of the first HTLC, it may not),
2070         //  * start routing a third HTLC from A to B,
2071         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2072         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2073         //  * deliver the first fulfill from B
2074         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2075         //    claim,
2076         //  * deliver A's response CS and RAA.
2077         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2078         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2079         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2080         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2081         let chanmon_cfgs = create_chanmon_cfgs(2);
2082         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2083         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2084         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2085         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2086
2087         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2088         // Route the first two HTLCs.
2089         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2090         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2091         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2092
2093         // Start routing the third HTLC (this is just used to get everyone in the right state).
2094         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2095         let send_1 = {
2096                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2097                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2098                 check_added_monitors!(nodes[0], 1);
2099                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2100                 assert_eq!(events.len(), 1);
2101                 SendEvent::from_event(events.remove(0))
2102         };
2103
2104         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2105         // initial fulfill/CS.
2106         nodes[1].node.claim_funds(payment_preimage_1);
2107         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2108         check_added_monitors!(nodes[1], 1);
2109         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2110
2111         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2112         // remove the second HTLC when we send the HTLC back from B to A.
2113         nodes[1].node.claim_funds(payment_preimage_2);
2114         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2115         check_added_monitors!(nodes[1], 1);
2116         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2117
2118         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2119         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2120         check_added_monitors!(nodes[0], 1);
2121         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2122         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2123
2124         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2125         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2126         check_added_monitors!(nodes[1], 1);
2127         // B is already AwaitingRAA, so cant generate a CS here
2128         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2129
2130         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2131         check_added_monitors!(nodes[1], 1);
2132         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2133
2134         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2135         check_added_monitors!(nodes[0], 1);
2136         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2137
2138         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2139         check_added_monitors!(nodes[1], 1);
2140         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2141
2142         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2143         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2144         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2145         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2146         // on-chain as necessary).
2147         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2148         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2149         check_added_monitors!(nodes[0], 1);
2150         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2151         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2152
2153         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2154         check_added_monitors!(nodes[1], 1);
2155         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2156
2157         expect_pending_htlcs_forwardable!(nodes[1]);
2158         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2159
2160         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2161         // resolve the second HTLC from A's point of view.
2162         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2163         check_added_monitors!(nodes[0], 1);
2164         expect_payment_path_successful!(nodes[0]);
2165         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2166
2167         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2168         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2169         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2170         let send_2 = {
2171                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2172                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2173                 check_added_monitors!(nodes[1], 1);
2174                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2175                 assert_eq!(events.len(), 1);
2176                 SendEvent::from_event(events.remove(0))
2177         };
2178
2179         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2180         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2181         check_added_monitors!(nodes[0], 1);
2182         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2183
2184         // Now just resolve all the outstanding messages/HTLCs for completeness...
2185
2186         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2187         check_added_monitors!(nodes[1], 1);
2188         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2189
2190         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2191         check_added_monitors!(nodes[1], 1);
2192
2193         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2194         check_added_monitors!(nodes[0], 1);
2195         expect_payment_path_successful!(nodes[0]);
2196         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2197
2198         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2199         check_added_monitors!(nodes[1], 1);
2200         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2201
2202         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2203         check_added_monitors!(nodes[0], 1);
2204
2205         expect_pending_htlcs_forwardable!(nodes[0]);
2206         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2207
2208         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2209         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2210 }
2211
2212 #[test]
2213 fn channel_monitor_network_test() {
2214         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2215         // tests that ChannelMonitor is able to recover from various states.
2216         let chanmon_cfgs = create_chanmon_cfgs(5);
2217         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2218         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2219         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2220
2221         // Create some initial channels
2222         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2223         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2224         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2225         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2226
2227         // Make sure all nodes are at the same starting height
2228         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2229         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2230         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2231         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2232         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2233
2234         // Rebalance the network a bit by relaying one payment through all the channels...
2235         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2236         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2237         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2238         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2239
2240         // Simple case with no pending HTLCs:
2241         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2242         check_added_monitors!(nodes[1], 1);
2243         check_closed_broadcast!(nodes[1], true);
2244         {
2245                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2246                 assert_eq!(node_txn.len(), 1);
2247                 mine_transaction(&nodes[0], &node_txn[0]);
2248                 check_added_monitors!(nodes[0], 1);
2249                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2250         }
2251         check_closed_broadcast!(nodes[0], true);
2252         assert_eq!(nodes[0].node.list_channels().len(), 0);
2253         assert_eq!(nodes[1].node.list_channels().len(), 1);
2254         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2255         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2256
2257         // One pending HTLC is discarded by the force-close:
2258         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2259
2260         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2261         // broadcasted until we reach the timelock time).
2262         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2263         check_closed_broadcast!(nodes[1], true);
2264         check_added_monitors!(nodes[1], 1);
2265         {
2266                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2267                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2268                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2269                 mine_transaction(&nodes[2], &node_txn[0]);
2270                 check_added_monitors!(nodes[2], 1);
2271                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2272         }
2273         check_closed_broadcast!(nodes[2], true);
2274         assert_eq!(nodes[1].node.list_channels().len(), 0);
2275         assert_eq!(nodes[2].node.list_channels().len(), 1);
2276         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2277         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2278
2279         macro_rules! claim_funds {
2280                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2281                         {
2282                                 $node.node.claim_funds($preimage);
2283                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2284                                 check_added_monitors!($node, 1);
2285
2286                                 let events = $node.node.get_and_clear_pending_msg_events();
2287                                 assert_eq!(events.len(), 1);
2288                                 match events[0] {
2289                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2290                                                 assert!(update_add_htlcs.is_empty());
2291                                                 assert!(update_fail_htlcs.is_empty());
2292                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2293                                         },
2294                                         _ => panic!("Unexpected event"),
2295                                 };
2296                         }
2297                 }
2298         }
2299
2300         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2301         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2302         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2303         check_added_monitors!(nodes[2], 1);
2304         check_closed_broadcast!(nodes[2], true);
2305         let node2_commitment_txid;
2306         {
2307                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2308                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2309                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2310                 node2_commitment_txid = node_txn[0].txid();
2311
2312                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2313                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2314                 mine_transaction(&nodes[3], &node_txn[0]);
2315                 check_added_monitors!(nodes[3], 1);
2316                 check_preimage_claim(&nodes[3], &node_txn);
2317         }
2318         check_closed_broadcast!(nodes[3], true);
2319         assert_eq!(nodes[2].node.list_channels().len(), 0);
2320         assert_eq!(nodes[3].node.list_channels().len(), 1);
2321         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2322         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2323
2324         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2325         // confusing us in the following tests.
2326         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2327
2328         // One pending HTLC to time out:
2329         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2330         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2331         // buffer space).
2332
2333         let (close_chan_update_1, close_chan_update_2) = {
2334                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2335                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2336                 assert_eq!(events.len(), 2);
2337                 let close_chan_update_1 = match events[0] {
2338                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2339                                 msg.clone()
2340                         },
2341                         _ => panic!("Unexpected event"),
2342                 };
2343                 match events[1] {
2344                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2345                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2346                         },
2347                         _ => panic!("Unexpected event"),
2348                 }
2349                 check_added_monitors!(nodes[3], 1);
2350
2351                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2352                 {
2353                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2354                         node_txn.retain(|tx| {
2355                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2356                                         false
2357                                 } else { true }
2358                         });
2359                 }
2360
2361                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2362
2363                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2364                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2365
2366                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2367                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2368                 assert_eq!(events.len(), 2);
2369                 let close_chan_update_2 = match events[0] {
2370                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2371                                 msg.clone()
2372                         },
2373                         _ => panic!("Unexpected event"),
2374                 };
2375                 match events[1] {
2376                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2377                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2378                         },
2379                         _ => panic!("Unexpected event"),
2380                 }
2381                 check_added_monitors!(nodes[4], 1);
2382                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2383
2384                 mine_transaction(&nodes[4], &node_txn[0]);
2385                 check_preimage_claim(&nodes[4], &node_txn);
2386                 (close_chan_update_1, close_chan_update_2)
2387         };
2388         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2389         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2390         assert_eq!(nodes[3].node.list_channels().len(), 0);
2391         assert_eq!(nodes[4].node.list_channels().len(), 0);
2392
2393         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2394                 ChannelMonitorUpdateStatus::Completed);
2395         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2396         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2397 }
2398
2399 #[test]
2400 fn test_justice_tx_htlc_timeout() {
2401         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2402         let mut alice_config = UserConfig::default();
2403         alice_config.channel_handshake_config.announced_channel = true;
2404         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2405         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2406         let mut bob_config = UserConfig::default();
2407         bob_config.channel_handshake_config.announced_channel = true;
2408         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2409         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2410         let user_cfgs = [Some(alice_config), Some(bob_config)];
2411         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2412         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2413         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2416         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2417         // Create some new channels:
2418         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2419
2420         // A pending HTLC which will be revoked:
2421         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2422         // Get the will-be-revoked local txn from nodes[0]
2423         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2424         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2425         assert_eq!(revoked_local_txn[0].input.len(), 1);
2426         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2427         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2428         assert_eq!(revoked_local_txn[1].input.len(), 1);
2429         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2430         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2431         // Revoke the old state
2432         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2433
2434         {
2435                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2436                 {
2437                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2438                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2439                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2440                         check_spends!(node_txn[0], revoked_local_txn[0]);
2441                         node_txn.swap_remove(0);
2442                 }
2443                 check_added_monitors!(nodes[1], 1);
2444                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2445                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2446
2447                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2448                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2449                 // Verify broadcast of revoked HTLC-timeout
2450                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2451                 check_added_monitors!(nodes[0], 1);
2452                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2453                 // Broadcast revoked HTLC-timeout on node 1
2454                 mine_transaction(&nodes[1], &node_txn[1]);
2455                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2456         }
2457         get_announce_close_broadcast_events(&nodes, 0, 1);
2458         assert_eq!(nodes[0].node.list_channels().len(), 0);
2459         assert_eq!(nodes[1].node.list_channels().len(), 0);
2460 }
2461
2462 #[test]
2463 fn test_justice_tx_htlc_success() {
2464         // Test justice txn built on revoked HTLC-Success tx, against both sides
2465         let mut alice_config = UserConfig::default();
2466         alice_config.channel_handshake_config.announced_channel = true;
2467         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2468         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2469         let mut bob_config = UserConfig::default();
2470         bob_config.channel_handshake_config.announced_channel = true;
2471         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2472         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2473         let user_cfgs = [Some(alice_config), Some(bob_config)];
2474         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2475         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2476         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2477         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2478         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2479         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2480         // Create some new channels:
2481         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2482
2483         // A pending HTLC which will be revoked:
2484         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2485         // Get the will-be-revoked local txn from B
2486         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2487         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2488         assert_eq!(revoked_local_txn[0].input.len(), 1);
2489         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2490         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2491         // Revoke the old state
2492         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2493         {
2494                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2495                 {
2496                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2497                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2498                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2499
2500                         check_spends!(node_txn[0], revoked_local_txn[0]);
2501                         node_txn.swap_remove(0);
2502                 }
2503                 check_added_monitors!(nodes[0], 1);
2504                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2505
2506                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2507                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2508                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2509                 check_added_monitors!(nodes[1], 1);
2510                 mine_transaction(&nodes[0], &node_txn[1]);
2511                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2512                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2513         }
2514         get_announce_close_broadcast_events(&nodes, 0, 1);
2515         assert_eq!(nodes[0].node.list_channels().len(), 0);
2516         assert_eq!(nodes[1].node.list_channels().len(), 0);
2517 }
2518
2519 #[test]
2520 fn revoked_output_claim() {
2521         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2522         // transaction is broadcast by its counterparty
2523         let chanmon_cfgs = create_chanmon_cfgs(2);
2524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2527         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2528         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2529         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2530         assert_eq!(revoked_local_txn.len(), 1);
2531         // Only output is the full channel value back to nodes[0]:
2532         assert_eq!(revoked_local_txn[0].output.len(), 1);
2533         // Send a payment through, updating everyone's latest commitment txn
2534         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2535
2536         // Inform nodes[1] that nodes[0] broadcast a stale tx
2537         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2538         check_added_monitors!(nodes[1], 1);
2539         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2540         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2541         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2542
2543         check_spends!(node_txn[0], revoked_local_txn[0]);
2544
2545         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2546         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2547         get_announce_close_broadcast_events(&nodes, 0, 1);
2548         check_added_monitors!(nodes[0], 1);
2549         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2550 }
2551
2552 #[test]
2553 fn claim_htlc_outputs_shared_tx() {
2554         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2555         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2556         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2559         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2560
2561         // Create some new channel:
2562         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2563
2564         // Rebalance the network to generate htlc in the two directions
2565         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2566         // 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
2567         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2568         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2569
2570         // Get the will-be-revoked local txn from node[0]
2571         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2572         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2573         assert_eq!(revoked_local_txn[0].input.len(), 1);
2574         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2575         assert_eq!(revoked_local_txn[1].input.len(), 1);
2576         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2577         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2578         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2579
2580         //Revoke the old state
2581         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2582
2583         {
2584                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2585                 check_added_monitors!(nodes[0], 1);
2586                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2587                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2588                 check_added_monitors!(nodes[1], 1);
2589                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2590                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2591                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2592
2593                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2594                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2595
2596                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2597                 check_spends!(node_txn[0], revoked_local_txn[0]);
2598
2599                 let mut witness_lens = BTreeSet::new();
2600                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2601                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2602                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2603                 assert_eq!(witness_lens.len(), 3);
2604                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2605                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2606                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2607
2608                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2609                 // ANTI_REORG_DELAY confirmations.
2610                 mine_transaction(&nodes[1], &node_txn[0]);
2611                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2612                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2613         }
2614         get_announce_close_broadcast_events(&nodes, 0, 1);
2615         assert_eq!(nodes[0].node.list_channels().len(), 0);
2616         assert_eq!(nodes[1].node.list_channels().len(), 0);
2617 }
2618
2619 #[test]
2620 fn claim_htlc_outputs_single_tx() {
2621         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2622         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2623         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2626         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2627
2628         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2629
2630         // Rebalance the network to generate htlc in the two directions
2631         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2632         // 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
2633         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2634         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2635         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2636
2637         // Get the will-be-revoked local txn from node[0]
2638         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2639
2640         //Revoke the old state
2641         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2642
2643         {
2644                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2645                 check_added_monitors!(nodes[0], 1);
2646                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2647                 check_added_monitors!(nodes[1], 1);
2648                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2649                 let mut events = nodes[0].node.get_and_clear_pending_events();
2650                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2651                 match events.last().unwrap() {
2652                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2653                         _ => panic!("Unexpected event"),
2654                 }
2655
2656                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2657                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2658
2659                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2660
2661                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2662                 assert_eq!(node_txn[0].input.len(), 1);
2663                 check_spends!(node_txn[0], chan_1.3);
2664                 assert_eq!(node_txn[1].input.len(), 1);
2665                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2666                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2667                 check_spends!(node_txn[1], node_txn[0]);
2668
2669                 // Filter out any non justice transactions.
2670                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2671                 assert!(node_txn.len() > 3);
2672
2673                 assert_eq!(node_txn[0].input.len(), 1);
2674                 assert_eq!(node_txn[1].input.len(), 1);
2675                 assert_eq!(node_txn[2].input.len(), 1);
2676
2677                 check_spends!(node_txn[0], revoked_local_txn[0]);
2678                 check_spends!(node_txn[1], revoked_local_txn[0]);
2679                 check_spends!(node_txn[2], revoked_local_txn[0]);
2680
2681                 let mut witness_lens = BTreeSet::new();
2682                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2683                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2684                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2685                 assert_eq!(witness_lens.len(), 3);
2686                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2687                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2688                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2689
2690                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2691                 // ANTI_REORG_DELAY confirmations.
2692                 mine_transaction(&nodes[1], &node_txn[0]);
2693                 mine_transaction(&nodes[1], &node_txn[1]);
2694                 mine_transaction(&nodes[1], &node_txn[2]);
2695                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2696                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2697         }
2698         get_announce_close_broadcast_events(&nodes, 0, 1);
2699         assert_eq!(nodes[0].node.list_channels().len(), 0);
2700         assert_eq!(nodes[1].node.list_channels().len(), 0);
2701 }
2702
2703 #[test]
2704 fn test_htlc_on_chain_success() {
2705         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2706         // the preimage backward accordingly. So here we test that ChannelManager is
2707         // broadcasting the right event to other nodes in payment path.
2708         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2709         // A --------------------> B ----------------------> C (preimage)
2710         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2711         // commitment transaction was broadcast.
2712         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2713         // towards B.
2714         // B should be able to claim via preimage if A then broadcasts its local tx.
2715         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2716         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2717         // PaymentSent event).
2718
2719         let chanmon_cfgs = create_chanmon_cfgs(3);
2720         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2721         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2722         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2723
2724         // Create some initial channels
2725         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2726         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2727
2728         // Ensure all nodes are at the same height
2729         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2730         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2731         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2732         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2733
2734         // Rebalance the network a bit by relaying one payment through all the channels...
2735         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2736         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2737
2738         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2739         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2740
2741         // Broadcast legit commitment tx from C on B's chain
2742         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2743         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2744         assert_eq!(commitment_tx.len(), 1);
2745         check_spends!(commitment_tx[0], chan_2.3);
2746         nodes[2].node.claim_funds(our_payment_preimage);
2747         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2748         nodes[2].node.claim_funds(our_payment_preimage_2);
2749         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2750         check_added_monitors!(nodes[2], 2);
2751         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2752         assert!(updates.update_add_htlcs.is_empty());
2753         assert!(updates.update_fail_htlcs.is_empty());
2754         assert!(updates.update_fail_malformed_htlcs.is_empty());
2755         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2756
2757         mine_transaction(&nodes[2], &commitment_tx[0]);
2758         check_closed_broadcast!(nodes[2], true);
2759         check_added_monitors!(nodes[2], 1);
2760         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2761         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2762         assert_eq!(node_txn.len(), 2);
2763         check_spends!(node_txn[0], commitment_tx[0]);
2764         check_spends!(node_txn[1], commitment_tx[0]);
2765         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2766         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2767         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2768         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2769         assert_eq!(node_txn[0].lock_time.0, 0);
2770         assert_eq!(node_txn[1].lock_time.0, 0);
2771
2772         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2773         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()]));
2774         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2775         {
2776                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2777                 assert_eq!(added_monitors.len(), 1);
2778                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2779                 added_monitors.clear();
2780         }
2781         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2782         assert_eq!(forwarded_events.len(), 3);
2783         match forwarded_events[0] {
2784                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2785                 _ => panic!("Unexpected event"),
2786         }
2787         let chan_id = Some(chan_1.2);
2788         match forwarded_events[1] {
2789                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2790                         assert_eq!(fee_earned_msat, Some(1000));
2791                         assert_eq!(prev_channel_id, chan_id);
2792                         assert_eq!(claim_from_onchain_tx, true);
2793                         assert_eq!(next_channel_id, Some(chan_2.2));
2794                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2795                 },
2796                 _ => panic!()
2797         }
2798         match forwarded_events[2] {
2799                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2800                         assert_eq!(fee_earned_msat, Some(1000));
2801                         assert_eq!(prev_channel_id, chan_id);
2802                         assert_eq!(claim_from_onchain_tx, true);
2803                         assert_eq!(next_channel_id, Some(chan_2.2));
2804                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2805                 },
2806                 _ => panic!()
2807         }
2808         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2809         {
2810                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2811                 assert_eq!(added_monitors.len(), 2);
2812                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2813                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2814                 added_monitors.clear();
2815         }
2816         assert_eq!(events.len(), 3);
2817
2818         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2819         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2820
2821         match nodes_2_event {
2822                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2823                 _ => panic!("Unexpected event"),
2824         }
2825
2826         match nodes_0_event {
2827                 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, .. } } => {
2828                         assert!(update_add_htlcs.is_empty());
2829                         assert!(update_fail_htlcs.is_empty());
2830                         assert_eq!(update_fulfill_htlcs.len(), 1);
2831                         assert!(update_fail_malformed_htlcs.is_empty());
2832                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2833                 },
2834                 _ => panic!("Unexpected event"),
2835         };
2836
2837         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2838         match events[0] {
2839                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2840                 _ => panic!("Unexpected event"),
2841         }
2842
2843         macro_rules! check_tx_local_broadcast {
2844                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2845                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2846                         assert_eq!(node_txn.len(), 2);
2847                         // Node[1]: 2 * HTLC-timeout tx
2848                         // Node[0]: 2 * HTLC-timeout tx
2849                         check_spends!(node_txn[0], $commitment_tx);
2850                         check_spends!(node_txn[1], $commitment_tx);
2851                         assert_ne!(node_txn[0].lock_time.0, 0);
2852                         assert_ne!(node_txn[1].lock_time.0, 0);
2853                         if $htlc_offered {
2854                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2855                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2856                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2857                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2858                         } else {
2859                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2860                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2861                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2862                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2863                         }
2864                         node_txn.clear();
2865                 } }
2866         }
2867         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2868         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2869
2870         // Broadcast legit commitment tx from A on B's chain
2871         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2872         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2873         check_spends!(node_a_commitment_tx[0], chan_1.3);
2874         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2875         check_closed_broadcast!(nodes[1], true);
2876         check_added_monitors!(nodes[1], 1);
2877         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2878         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2879         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2880         let commitment_spend =
2881                 if node_txn.len() == 1 {
2882                         &node_txn[0]
2883                 } else {
2884                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2885                         // FullBlockViaListen
2886                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2887                                 check_spends!(node_txn[1], commitment_tx[0]);
2888                                 check_spends!(node_txn[2], commitment_tx[0]);
2889                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2890                                 &node_txn[0]
2891                         } else {
2892                                 check_spends!(node_txn[0], commitment_tx[0]);
2893                                 check_spends!(node_txn[1], commitment_tx[0]);
2894                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2895                                 &node_txn[2]
2896                         }
2897                 };
2898
2899         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2900         assert_eq!(commitment_spend.input.len(), 2);
2901         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2902         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2903         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2904         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2905         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2906         // we already checked the same situation with A.
2907
2908         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2909         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2910         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2911         check_closed_broadcast!(nodes[0], true);
2912         check_added_monitors!(nodes[0], 1);
2913         let events = nodes[0].node.get_and_clear_pending_events();
2914         assert_eq!(events.len(), 5);
2915         let mut first_claimed = false;
2916         for event in events {
2917                 match event {
2918                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2919                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2920                                         assert!(!first_claimed);
2921                                         first_claimed = true;
2922                                 } else {
2923                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2924                                         assert_eq!(payment_hash, payment_hash_2);
2925                                 }
2926                         },
2927                         Event::PaymentPathSuccessful { .. } => {},
2928                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2929                         _ => panic!("Unexpected event"),
2930                 }
2931         }
2932         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2933 }
2934
2935 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2936         // Test that in case of a unilateral close onchain, we detect the state of output and
2937         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2938         // broadcasting the right event to other nodes in payment path.
2939         // A ------------------> B ----------------------> C (timeout)
2940         //    B's commitment tx                 C's commitment tx
2941         //            \                                  \
2942         //         B's HTLC timeout tx               B's timeout tx
2943
2944         let chanmon_cfgs = create_chanmon_cfgs(3);
2945         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2946         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2947         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2948         *nodes[0].connect_style.borrow_mut() = connect_style;
2949         *nodes[1].connect_style.borrow_mut() = connect_style;
2950         *nodes[2].connect_style.borrow_mut() = connect_style;
2951
2952         // Create some intial channels
2953         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2954         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2955
2956         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2957         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2958         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2959
2960         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2961
2962         // Broadcast legit commitment tx from C on B's chain
2963         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2964         check_spends!(commitment_tx[0], chan_2.3);
2965         nodes[2].node.fail_htlc_backwards(&payment_hash);
2966         check_added_monitors!(nodes[2], 0);
2967         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2968         check_added_monitors!(nodes[2], 1);
2969
2970         let events = nodes[2].node.get_and_clear_pending_msg_events();
2971         assert_eq!(events.len(), 1);
2972         match events[0] {
2973                 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, .. } } => {
2974                         assert!(update_add_htlcs.is_empty());
2975                         assert!(!update_fail_htlcs.is_empty());
2976                         assert!(update_fulfill_htlcs.is_empty());
2977                         assert!(update_fail_malformed_htlcs.is_empty());
2978                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2979                 },
2980                 _ => panic!("Unexpected event"),
2981         };
2982         mine_transaction(&nodes[2], &commitment_tx[0]);
2983         check_closed_broadcast!(nodes[2], true);
2984         check_added_monitors!(nodes[2], 1);
2985         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2986         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2987         assert_eq!(node_txn.len(), 0);
2988
2989         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2990         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2991         mine_transaction(&nodes[1], &commitment_tx[0]);
2992         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2993         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2994         let timeout_tx = {
2995                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2996                 if nodes[1].connect_style.borrow().skips_blocks() {
2997                         assert_eq!(txn.len(), 1);
2998                 } else {
2999                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3000                 }
3001                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3002                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3003                 txn.remove(0)
3004         };
3005
3006         mine_transaction(&nodes[1], &timeout_tx);
3007         check_added_monitors!(nodes[1], 1);
3008         check_closed_broadcast!(nodes[1], true);
3009
3010         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3011
3012         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 }]);
3013         check_added_monitors!(nodes[1], 1);
3014         let events = nodes[1].node.get_and_clear_pending_msg_events();
3015         assert_eq!(events.len(), 1);
3016         match events[0] {
3017                 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, .. } } => {
3018                         assert!(update_add_htlcs.is_empty());
3019                         assert!(!update_fail_htlcs.is_empty());
3020                         assert!(update_fulfill_htlcs.is_empty());
3021                         assert!(update_fail_malformed_htlcs.is_empty());
3022                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3023                 },
3024                 _ => panic!("Unexpected event"),
3025         };
3026
3027         // Broadcast legit commitment tx from B on A's chain
3028         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3029         check_spends!(commitment_tx[0], chan_1.3);
3030
3031         mine_transaction(&nodes[0], &commitment_tx[0]);
3032         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3033
3034         check_closed_broadcast!(nodes[0], true);
3035         check_added_monitors!(nodes[0], 1);
3036         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3037         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3038         assert_eq!(node_txn.len(), 1);
3039         check_spends!(node_txn[0], commitment_tx[0]);
3040         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3041 }
3042
3043 #[test]
3044 fn test_htlc_on_chain_timeout() {
3045         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3046         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3047         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3048 }
3049
3050 #[test]
3051 fn test_simple_commitment_revoked_fail_backward() {
3052         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3053         // and fail backward accordingly.
3054
3055         let chanmon_cfgs = create_chanmon_cfgs(3);
3056         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3057         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3058         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3059
3060         // Create some initial channels
3061         create_announced_chan_between_nodes(&nodes, 0, 1);
3062         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3063
3064         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3065         // Get the will-be-revoked local txn from nodes[2]
3066         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3067         // Revoke the old state
3068         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3069
3070         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3071
3072         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3073         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3074         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3075         check_added_monitors!(nodes[1], 1);
3076         check_closed_broadcast!(nodes[1], true);
3077
3078         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 }]);
3079         check_added_monitors!(nodes[1], 1);
3080         let events = nodes[1].node.get_and_clear_pending_msg_events();
3081         assert_eq!(events.len(), 1);
3082         match events[0] {
3083                 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, .. } } => {
3084                         assert!(update_add_htlcs.is_empty());
3085                         assert_eq!(update_fail_htlcs.len(), 1);
3086                         assert!(update_fulfill_htlcs.is_empty());
3087                         assert!(update_fail_malformed_htlcs.is_empty());
3088                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3089
3090                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3091                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3092                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3093                 },
3094                 _ => panic!("Unexpected event"),
3095         }
3096 }
3097
3098 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3099         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3100         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3101         // commitment transaction anymore.
3102         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3103         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3104         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3105         // technically disallowed and we should probably handle it reasonably.
3106         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3107         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3108         // transactions:
3109         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3110         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3111         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3112         //   and once they revoke the previous commitment transaction (allowing us to send a new
3113         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3114         let chanmon_cfgs = create_chanmon_cfgs(3);
3115         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3116         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3117         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3118
3119         // Create some initial channels
3120         create_announced_chan_between_nodes(&nodes, 0, 1);
3121         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3122
3123         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 });
3124         // Get the will-be-revoked local txn from nodes[2]
3125         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3126         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3127         // Revoke the old state
3128         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3129
3130         let value = if use_dust {
3131                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3132                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3133                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3134                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3135         } else { 3000000 };
3136
3137         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3138         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3139         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3140
3141         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3142         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3143         check_added_monitors!(nodes[2], 1);
3144         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3145         assert!(updates.update_add_htlcs.is_empty());
3146         assert!(updates.update_fulfill_htlcs.is_empty());
3147         assert!(updates.update_fail_malformed_htlcs.is_empty());
3148         assert_eq!(updates.update_fail_htlcs.len(), 1);
3149         assert!(updates.update_fee.is_none());
3150         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3151         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3152         // Drop the last RAA from 3 -> 2
3153
3154         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3155         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3156         check_added_monitors!(nodes[2], 1);
3157         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3158         assert!(updates.update_add_htlcs.is_empty());
3159         assert!(updates.update_fulfill_htlcs.is_empty());
3160         assert!(updates.update_fail_malformed_htlcs.is_empty());
3161         assert_eq!(updates.update_fail_htlcs.len(), 1);
3162         assert!(updates.update_fee.is_none());
3163         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3164         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3165         check_added_monitors!(nodes[1], 1);
3166         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3167         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3168         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3169         check_added_monitors!(nodes[2], 1);
3170
3171         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3172         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3173         check_added_monitors!(nodes[2], 1);
3174         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3175         assert!(updates.update_add_htlcs.is_empty());
3176         assert!(updates.update_fulfill_htlcs.is_empty());
3177         assert!(updates.update_fail_malformed_htlcs.is_empty());
3178         assert_eq!(updates.update_fail_htlcs.len(), 1);
3179         assert!(updates.update_fee.is_none());
3180         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3181         // At this point first_payment_hash has dropped out of the latest two commitment
3182         // transactions that nodes[1] is tracking...
3183         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3184         check_added_monitors!(nodes[1], 1);
3185         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3186         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3187         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3188         check_added_monitors!(nodes[2], 1);
3189
3190         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3191         // on nodes[2]'s RAA.
3192         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3193         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3194                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3195         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3196         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3197         check_added_monitors!(nodes[1], 0);
3198
3199         if deliver_bs_raa {
3200                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3201                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3202                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3203                 check_added_monitors!(nodes[1], 1);
3204                 let events = nodes[1].node.get_and_clear_pending_events();
3205                 assert_eq!(events.len(), 2);
3206                 match events[0] {
3207                         Event::PendingHTLCsForwardable { .. } => { },
3208                         _ => panic!("Unexpected event"),
3209                 };
3210                 match events[1] {
3211                         Event::HTLCHandlingFailed { .. } => { },
3212                         _ => panic!("Unexpected event"),
3213                 }
3214                 // Deliberately don't process the pending fail-back so they all fail back at once after
3215                 // block connection just like the !deliver_bs_raa case
3216         }
3217
3218         let mut failed_htlcs = HashSet::new();
3219         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3220
3221         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3222         check_added_monitors!(nodes[1], 1);
3223         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3224
3225         let events = nodes[1].node.get_and_clear_pending_events();
3226         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3227         match events[0] {
3228                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3229                 _ => panic!("Unexepected event"),
3230         }
3231         match events[1] {
3232                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3233                         assert_eq!(*payment_hash, fourth_payment_hash);
3234                 },
3235                 _ => panic!("Unexpected event"),
3236         }
3237         match events[2] {
3238                 Event::PaymentFailed { ref payment_hash, .. } => {
3239                         assert_eq!(*payment_hash, fourth_payment_hash);
3240                 },
3241                 _ => panic!("Unexpected event"),
3242         }
3243
3244         nodes[1].node.process_pending_htlc_forwards();
3245         check_added_monitors!(nodes[1], 1);
3246
3247         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3248         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3249
3250         if deliver_bs_raa {
3251                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3252                 match nodes_2_event {
3253                         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, .. } } => {
3254                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3255                                 assert_eq!(update_add_htlcs.len(), 1);
3256                                 assert!(update_fulfill_htlcs.is_empty());
3257                                 assert!(update_fail_htlcs.is_empty());
3258                                 assert!(update_fail_malformed_htlcs.is_empty());
3259                         },
3260                         _ => panic!("Unexpected event"),
3261                 }
3262         }
3263
3264         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3265         match nodes_2_event {
3266                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3267                         assert_eq!(channel_id, chan_2.2);
3268                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3269                 },
3270                 _ => panic!("Unexpected event"),
3271         }
3272
3273         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3274         match nodes_0_event {
3275                 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, .. } } => {
3276                         assert!(update_add_htlcs.is_empty());
3277                         assert_eq!(update_fail_htlcs.len(), 3);
3278                         assert!(update_fulfill_htlcs.is_empty());
3279                         assert!(update_fail_malformed_htlcs.is_empty());
3280                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3281
3282                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3283                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3284                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3285
3286                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3287
3288                         let events = nodes[0].node.get_and_clear_pending_events();
3289                         assert_eq!(events.len(), 6);
3290                         match events[0] {
3291                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3292                                         assert!(failed_htlcs.insert(payment_hash.0));
3293                                         // If we delivered B's RAA we got an unknown preimage error, not something
3294                                         // that we should update our routing table for.
3295                                         if !deliver_bs_raa {
3296                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3297                                         }
3298                                 },
3299                                 _ => panic!("Unexpected event"),
3300                         }
3301                         match events[1] {
3302                                 Event::PaymentFailed { ref payment_hash, .. } => {
3303                                         assert_eq!(*payment_hash, first_payment_hash);
3304                                 },
3305                                 _ => panic!("Unexpected event"),
3306                         }
3307                         match events[2] {
3308                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3309                                         assert!(failed_htlcs.insert(payment_hash.0));
3310                                 },
3311                                 _ => panic!("Unexpected event"),
3312                         }
3313                         match events[3] {
3314                                 Event::PaymentFailed { ref payment_hash, .. } => {
3315                                         assert_eq!(*payment_hash, second_payment_hash);
3316                                 },
3317                                 _ => panic!("Unexpected event"),
3318                         }
3319                         match events[4] {
3320                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3321                                         assert!(failed_htlcs.insert(payment_hash.0));
3322                                 },
3323                                 _ => panic!("Unexpected event"),
3324                         }
3325                         match events[5] {
3326                                 Event::PaymentFailed { ref payment_hash, .. } => {
3327                                         assert_eq!(*payment_hash, third_payment_hash);
3328                                 },
3329                                 _ => panic!("Unexpected event"),
3330                         }
3331                 },
3332                 _ => panic!("Unexpected event"),
3333         }
3334
3335         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3336         match events[0] {
3337                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3338                 _ => panic!("Unexpected event"),
3339         }
3340
3341         assert!(failed_htlcs.contains(&first_payment_hash.0));
3342         assert!(failed_htlcs.contains(&second_payment_hash.0));
3343         assert!(failed_htlcs.contains(&third_payment_hash.0));
3344 }
3345
3346 #[test]
3347 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3348         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3349         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3350         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3351         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3352 }
3353
3354 #[test]
3355 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3356         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3357         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3358         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3359         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3360 }
3361
3362 #[test]
3363 fn fail_backward_pending_htlc_upon_channel_failure() {
3364         let chanmon_cfgs = create_chanmon_cfgs(2);
3365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3367         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3368         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3369
3370         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3371         {
3372                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3373                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3374                         PaymentId(payment_hash.0)).unwrap();
3375                 check_added_monitors!(nodes[0], 1);
3376
3377                 let payment_event = {
3378                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3379                         assert_eq!(events.len(), 1);
3380                         SendEvent::from_event(events.remove(0))
3381                 };
3382                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3383                 assert_eq!(payment_event.msgs.len(), 1);
3384         }
3385
3386         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3387         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3388         {
3389                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3390                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3391                 check_added_monitors!(nodes[0], 0);
3392
3393                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3394         }
3395
3396         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3397         {
3398                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3399
3400                 let secp_ctx = Secp256k1::new();
3401                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3402                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3403                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3404                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3405                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3406                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3407
3408                 // Send a 0-msat update_add_htlc to fail the channel.
3409                 let update_add_htlc = msgs::UpdateAddHTLC {
3410                         channel_id: chan.2,
3411                         htlc_id: 0,
3412                         amount_msat: 0,
3413                         payment_hash,
3414                         cltv_expiry,
3415                         onion_routing_packet,
3416                         skimmed_fee_msat: None,
3417                 };
3418                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3419         }
3420         let events = nodes[0].node.get_and_clear_pending_events();
3421         assert_eq!(events.len(), 3);
3422         // Check that Alice fails backward the pending HTLC from the second payment.
3423         match events[0] {
3424                 Event::PaymentPathFailed { payment_hash, .. } => {
3425                         assert_eq!(payment_hash, failed_payment_hash);
3426                 },
3427                 _ => panic!("Unexpected event"),
3428         }
3429         match events[1] {
3430                 Event::PaymentFailed { payment_hash, .. } => {
3431                         assert_eq!(payment_hash, failed_payment_hash);
3432                 },
3433                 _ => panic!("Unexpected event"),
3434         }
3435         match events[2] {
3436                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3437                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3438                 },
3439                 _ => panic!("Unexpected event {:?}", events[1]),
3440         }
3441         check_closed_broadcast!(nodes[0], true);
3442         check_added_monitors!(nodes[0], 1);
3443 }
3444
3445 #[test]
3446 fn test_htlc_ignore_latest_remote_commitment() {
3447         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3448         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3449         let chanmon_cfgs = create_chanmon_cfgs(2);
3450         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3451         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3452         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3453         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3454                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3455                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3456                 // connect_style.
3457                 return;
3458         }
3459         create_announced_chan_between_nodes(&nodes, 0, 1);
3460
3461         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3462         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3463         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3464         check_closed_broadcast!(nodes[0], true);
3465         check_added_monitors!(nodes[0], 1);
3466         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3467
3468         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3469         assert_eq!(node_txn.len(), 3);
3470         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3471
3472         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3473         connect_block(&nodes[1], &block);
3474         check_closed_broadcast!(nodes[1], true);
3475         check_added_monitors!(nodes[1], 1);
3476         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3477
3478         // Duplicate the connect_block call since this may happen due to other listeners
3479         // registering new transactions
3480         connect_block(&nodes[1], &block);
3481 }
3482
3483 #[test]
3484 fn test_force_close_fail_back() {
3485         // Check which HTLCs are failed-backwards on channel force-closure
3486         let chanmon_cfgs = create_chanmon_cfgs(3);
3487         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3488         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3489         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3490         create_announced_chan_between_nodes(&nodes, 0, 1);
3491         create_announced_chan_between_nodes(&nodes, 1, 2);
3492
3493         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3494
3495         let mut payment_event = {
3496                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3497                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3498                 check_added_monitors!(nodes[0], 1);
3499
3500                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3501                 assert_eq!(events.len(), 1);
3502                 SendEvent::from_event(events.remove(0))
3503         };
3504
3505         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3506         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3507
3508         expect_pending_htlcs_forwardable!(nodes[1]);
3509
3510         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3511         assert_eq!(events_2.len(), 1);
3512         payment_event = SendEvent::from_event(events_2.remove(0));
3513         assert_eq!(payment_event.msgs.len(), 1);
3514
3515         check_added_monitors!(nodes[1], 1);
3516         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3517         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3518         check_added_monitors!(nodes[2], 1);
3519         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3520
3521         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3522         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3523         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3524
3525         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3526         check_closed_broadcast!(nodes[2], true);
3527         check_added_monitors!(nodes[2], 1);
3528         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3529         let tx = {
3530                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3531                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3532                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3533                 // back to nodes[1] upon timeout otherwise.
3534                 assert_eq!(node_txn.len(), 1);
3535                 node_txn.remove(0)
3536         };
3537
3538         mine_transaction(&nodes[1], &tx);
3539
3540         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3541         check_closed_broadcast!(nodes[1], true);
3542         check_added_monitors!(nodes[1], 1);
3543         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3544
3545         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3546         {
3547                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3548                         .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);
3549         }
3550         mine_transaction(&nodes[2], &tx);
3551         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3552         assert_eq!(node_txn.len(), 1);
3553         assert_eq!(node_txn[0].input.len(), 1);
3554         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3555         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3556         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3557
3558         check_spends!(node_txn[0], tx);
3559 }
3560
3561 #[test]
3562 fn test_dup_events_on_peer_disconnect() {
3563         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3564         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3565         // as we used to generate the event immediately upon receipt of the payment preimage in the
3566         // update_fulfill_htlc message.
3567
3568         let chanmon_cfgs = create_chanmon_cfgs(2);
3569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3572         create_announced_chan_between_nodes(&nodes, 0, 1);
3573
3574         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3575
3576         nodes[1].node.claim_funds(payment_preimage);
3577         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3578         check_added_monitors!(nodes[1], 1);
3579         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3580         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3581         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3582
3583         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3584         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3585
3586         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3587         expect_payment_path_successful!(nodes[0]);
3588 }
3589
3590 #[test]
3591 fn test_peer_disconnected_before_funding_broadcasted() {
3592         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3593         // before the funding transaction has been broadcasted.
3594         let chanmon_cfgs = create_chanmon_cfgs(2);
3595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3597         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3598
3599         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3600         // broadcasted, even though it's created by `nodes[0]`.
3601         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();
3602         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3603         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3604         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3605         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3606
3607         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3608         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3609
3610         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3611
3612         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3613         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3614
3615         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3616         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3617         // broadcasted.
3618         {
3619                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3620         }
3621
3622         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3623         // disconnected before the funding transaction was broadcasted.
3624         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3625         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3626
3627         check_closed_event(&nodes[0], 1, ClosureReason::DisconnectedPeer, false);
3628         check_closed_event(&nodes[1], 1, ClosureReason::DisconnectedPeer, false);
3629 }
3630
3631 #[test]
3632 fn test_simple_peer_disconnect() {
3633         // Test that we can reconnect when there are no lost messages
3634         let chanmon_cfgs = create_chanmon_cfgs(3);
3635         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3636         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3637         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3638         create_announced_chan_between_nodes(&nodes, 0, 1);
3639         create_announced_chan_between_nodes(&nodes, 1, 2);
3640
3641         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3642         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3643         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3644
3645         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3646         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3648         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3649
3650         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3651         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3652         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3653
3654         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3655         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3656         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3657         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3658
3659         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3660         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3661
3662         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3663         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3664
3665         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3666         {
3667                 let events = nodes[0].node.get_and_clear_pending_events();
3668                 assert_eq!(events.len(), 4);
3669                 match events[0] {
3670                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3671                                 assert_eq!(payment_preimage, payment_preimage_3);
3672                                 assert_eq!(payment_hash, payment_hash_3);
3673                         },
3674                         _ => panic!("Unexpected event"),
3675                 }
3676                 match events[1] {
3677                         Event::PaymentPathSuccessful { .. } => {},
3678                         _ => panic!("Unexpected event"),
3679                 }
3680                 match events[2] {
3681                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3682                                 assert_eq!(payment_hash, payment_hash_5);
3683                                 assert!(payment_failed_permanently);
3684                         },
3685                         _ => panic!("Unexpected event"),
3686                 }
3687                 match events[3] {
3688                         Event::PaymentFailed { payment_hash, .. } => {
3689                                 assert_eq!(payment_hash, payment_hash_5);
3690                         },
3691                         _ => panic!("Unexpected event"),
3692                 }
3693         }
3694
3695         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3696         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3697 }
3698
3699 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3700         // Test that we can reconnect when in-flight HTLC updates get dropped
3701         let chanmon_cfgs = create_chanmon_cfgs(2);
3702         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3703         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3704         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3705
3706         let mut as_channel_ready = None;
3707         let channel_id = if messages_delivered == 0 {
3708                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3709                 as_channel_ready = Some(channel_ready);
3710                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3711                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3712                 // it before the channel_reestablish message.
3713                 chan_id
3714         } else {
3715                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3716         };
3717
3718         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3719
3720         let payment_event = {
3721                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3722                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3723                 check_added_monitors!(nodes[0], 1);
3724
3725                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3726                 assert_eq!(events.len(), 1);
3727                 SendEvent::from_event(events.remove(0))
3728         };
3729         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3730
3731         if messages_delivered < 2 {
3732                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3733         } else {
3734                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3735                 if messages_delivered >= 3 {
3736                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3737                         check_added_monitors!(nodes[1], 1);
3738                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3739
3740                         if messages_delivered >= 4 {
3741                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3742                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3743                                 check_added_monitors!(nodes[0], 1);
3744
3745                                 if messages_delivered >= 5 {
3746                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3747                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3748                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3749                                         check_added_monitors!(nodes[0], 1);
3750
3751                                         if messages_delivered >= 6 {
3752                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3753                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3754                                                 check_added_monitors!(nodes[1], 1);
3755                                         }
3756                                 }
3757                         }
3758                 }
3759         }
3760
3761         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3762         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3763         if messages_delivered < 3 {
3764                 if simulate_broken_lnd {
3765                         // lnd has a long-standing bug where they send a channel_ready prior to a
3766                         // channel_reestablish if you reconnect prior to channel_ready time.
3767                         //
3768                         // Here we simulate that behavior, delivering a channel_ready immediately on
3769                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3770                         // in `reconnect_nodes` but we currently don't fail based on that.
3771                         //
3772                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3773                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3774                 }
3775                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3776                 // received on either side, both sides will need to resend them.
3777                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3778         } else if messages_delivered == 3 {
3779                 // nodes[0] still wants its RAA + commitment_signed
3780                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3781         } else if messages_delivered == 4 {
3782                 // nodes[0] still wants its commitment_signed
3783                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3784         } else if messages_delivered == 5 {
3785                 // nodes[1] still wants its final RAA
3786                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3787         } else if messages_delivered == 6 {
3788                 // Everything was delivered...
3789                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3790         }
3791
3792         let events_1 = nodes[1].node.get_and_clear_pending_events();
3793         if messages_delivered == 0 {
3794                 assert_eq!(events_1.len(), 2);
3795                 match events_1[0] {
3796                         Event::ChannelReady { .. } => { },
3797                         _ => panic!("Unexpected event"),
3798                 };
3799                 match events_1[1] {
3800                         Event::PendingHTLCsForwardable { .. } => { },
3801                         _ => panic!("Unexpected event"),
3802                 };
3803         } else {
3804                 assert_eq!(events_1.len(), 1);
3805                 match events_1[0] {
3806                         Event::PendingHTLCsForwardable { .. } => { },
3807                         _ => panic!("Unexpected event"),
3808                 };
3809         }
3810
3811         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3812         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3813         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3814
3815         nodes[1].node.process_pending_htlc_forwards();
3816
3817         let events_2 = nodes[1].node.get_and_clear_pending_events();
3818         assert_eq!(events_2.len(), 1);
3819         match events_2[0] {
3820                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3821                         assert_eq!(payment_hash_1, *payment_hash);
3822                         assert_eq!(amount_msat, 1_000_000);
3823                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3824                         assert_eq!(via_channel_id, Some(channel_id));
3825                         match &purpose {
3826                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3827                                         assert!(payment_preimage.is_none());
3828                                         assert_eq!(payment_secret_1, *payment_secret);
3829                                 },
3830                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3831                         }
3832                 },
3833                 _ => panic!("Unexpected event"),
3834         }
3835
3836         nodes[1].node.claim_funds(payment_preimage_1);
3837         check_added_monitors!(nodes[1], 1);
3838         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3839
3840         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3841         assert_eq!(events_3.len(), 1);
3842         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3843                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3844                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3845                         assert!(updates.update_add_htlcs.is_empty());
3846                         assert!(updates.update_fail_htlcs.is_empty());
3847                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3848                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3849                         assert!(updates.update_fee.is_none());
3850                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3851                 },
3852                 _ => panic!("Unexpected event"),
3853         };
3854
3855         if messages_delivered >= 1 {
3856                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3857
3858                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3859                 assert_eq!(events_4.len(), 1);
3860                 match events_4[0] {
3861                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3862                                 assert_eq!(payment_preimage_1, *payment_preimage);
3863                                 assert_eq!(payment_hash_1, *payment_hash);
3864                         },
3865                         _ => panic!("Unexpected event"),
3866                 }
3867
3868                 if messages_delivered >= 2 {
3869                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3870                         check_added_monitors!(nodes[0], 1);
3871                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3872
3873                         if messages_delivered >= 3 {
3874                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3875                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3876                                 check_added_monitors!(nodes[1], 1);
3877
3878                                 if messages_delivered >= 4 {
3879                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3880                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3881                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3882                                         check_added_monitors!(nodes[1], 1);
3883
3884                                         if messages_delivered >= 5 {
3885                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3886                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3887                                                 check_added_monitors!(nodes[0], 1);
3888                                         }
3889                                 }
3890                         }
3891                 }
3892         }
3893
3894         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3895         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3896         if messages_delivered < 2 {
3897                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3898                 if messages_delivered < 1 {
3899                         expect_payment_sent!(nodes[0], payment_preimage_1);
3900                 } else {
3901                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3902                 }
3903         } else if messages_delivered == 2 {
3904                 // nodes[0] still wants its RAA + commitment_signed
3905                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3906         } else if messages_delivered == 3 {
3907                 // nodes[0] still wants its commitment_signed
3908                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3909         } else if messages_delivered == 4 {
3910                 // nodes[1] still wants its final RAA
3911                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3912         } else if messages_delivered == 5 {
3913                 // Everything was delivered...
3914                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3915         }
3916
3917         if messages_delivered == 1 || messages_delivered == 2 {
3918                 expect_payment_path_successful!(nodes[0]);
3919         }
3920         if messages_delivered <= 5 {
3921                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3922                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3923         }
3924         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3925
3926         if messages_delivered > 2 {
3927                 expect_payment_path_successful!(nodes[0]);
3928         }
3929
3930         // Channel should still work fine...
3931         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3932         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3933         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3934 }
3935
3936 #[test]
3937 fn test_drop_messages_peer_disconnect_a() {
3938         do_test_drop_messages_peer_disconnect(0, true);
3939         do_test_drop_messages_peer_disconnect(0, false);
3940         do_test_drop_messages_peer_disconnect(1, false);
3941         do_test_drop_messages_peer_disconnect(2, false);
3942 }
3943
3944 #[test]
3945 fn test_drop_messages_peer_disconnect_b() {
3946         do_test_drop_messages_peer_disconnect(3, false);
3947         do_test_drop_messages_peer_disconnect(4, false);
3948         do_test_drop_messages_peer_disconnect(5, false);
3949         do_test_drop_messages_peer_disconnect(6, false);
3950 }
3951
3952 #[test]
3953 fn test_channel_ready_without_best_block_updated() {
3954         // Previously, if we were offline when a funding transaction was locked in, and then we came
3955         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3956         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3957         // channel_ready immediately instead.
3958         let chanmon_cfgs = create_chanmon_cfgs(2);
3959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3961         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3962         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3963
3964         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3965
3966         let conf_height = nodes[0].best_block_info().1 + 1;
3967         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3968         let block_txn = [funding_tx];
3969         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3970         let conf_block_header = nodes[0].get_block_header(conf_height);
3971         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3972
3973         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3974         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3975         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3976 }
3977
3978 #[test]
3979 fn test_drop_messages_peer_disconnect_dual_htlc() {
3980         // Test that we can handle reconnecting when both sides of a channel have pending
3981         // commitment_updates when we disconnect.
3982         let chanmon_cfgs = create_chanmon_cfgs(2);
3983         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3984         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3985         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3986         create_announced_chan_between_nodes(&nodes, 0, 1);
3987
3988         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3989
3990         // Now try to send a second payment which will fail to send
3991         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3992         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3993                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3994         check_added_monitors!(nodes[0], 1);
3995
3996         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3997         assert_eq!(events_1.len(), 1);
3998         match events_1[0] {
3999                 MessageSendEvent::UpdateHTLCs { .. } => {},
4000                 _ => panic!("Unexpected event"),
4001         }
4002
4003         nodes[1].node.claim_funds(payment_preimage_1);
4004         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4005         check_added_monitors!(nodes[1], 1);
4006
4007         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4008         assert_eq!(events_2.len(), 1);
4009         match events_2[0] {
4010                 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 } } => {
4011                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4012                         assert!(update_add_htlcs.is_empty());
4013                         assert_eq!(update_fulfill_htlcs.len(), 1);
4014                         assert!(update_fail_htlcs.is_empty());
4015                         assert!(update_fail_malformed_htlcs.is_empty());
4016                         assert!(update_fee.is_none());
4017
4018                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4019                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4020                         assert_eq!(events_3.len(), 1);
4021                         match events_3[0] {
4022                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4023                                         assert_eq!(*payment_preimage, payment_preimage_1);
4024                                         assert_eq!(*payment_hash, payment_hash_1);
4025                                 },
4026                                 _ => panic!("Unexpected event"),
4027                         }
4028
4029                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4030                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4031                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4032                         check_added_monitors!(nodes[0], 1);
4033                 },
4034                 _ => panic!("Unexpected event"),
4035         }
4036
4037         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4038         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4039
4040         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4041                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4042         }, true).unwrap();
4043         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4044         assert_eq!(reestablish_1.len(), 1);
4045         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4046                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4047         }, false).unwrap();
4048         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4049         assert_eq!(reestablish_2.len(), 1);
4050
4051         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4052         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4053         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4054         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4055
4056         assert!(as_resp.0.is_none());
4057         assert!(bs_resp.0.is_none());
4058
4059         assert!(bs_resp.1.is_none());
4060         assert!(bs_resp.2.is_none());
4061
4062         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4063
4064         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4065         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4066         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4067         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4068         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4069         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4070         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4071         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4072         // No commitment_signed so get_event_msg's assert(len == 1) passes
4073         check_added_monitors!(nodes[1], 1);
4074
4075         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4076         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4077         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4078         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4079         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4080         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4081         assert!(bs_second_commitment_signed.update_fee.is_none());
4082         check_added_monitors!(nodes[1], 1);
4083
4084         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4085         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4086         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4087         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4088         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4089         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4090         assert!(as_commitment_signed.update_fee.is_none());
4091         check_added_monitors!(nodes[0], 1);
4092
4093         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4094         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4095         // No commitment_signed so get_event_msg's assert(len == 1) passes
4096         check_added_monitors!(nodes[0], 1);
4097
4098         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4099         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4100         // No commitment_signed so get_event_msg's assert(len == 1) passes
4101         check_added_monitors!(nodes[1], 1);
4102
4103         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4104         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4105         check_added_monitors!(nodes[1], 1);
4106
4107         expect_pending_htlcs_forwardable!(nodes[1]);
4108
4109         let events_5 = nodes[1].node.get_and_clear_pending_events();
4110         assert_eq!(events_5.len(), 1);
4111         match events_5[0] {
4112                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4113                         assert_eq!(payment_hash_2, *payment_hash);
4114                         match &purpose {
4115                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4116                                         assert!(payment_preimage.is_none());
4117                                         assert_eq!(payment_secret_2, *payment_secret);
4118                                 },
4119                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4120                         }
4121                 },
4122                 _ => panic!("Unexpected event"),
4123         }
4124
4125         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4126         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4127         check_added_monitors!(nodes[0], 1);
4128
4129         expect_payment_path_successful!(nodes[0]);
4130         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4131 }
4132
4133 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4134         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4135         // to avoid our counterparty failing the channel.
4136         let chanmon_cfgs = create_chanmon_cfgs(2);
4137         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4138         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4139         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4140
4141         create_announced_chan_between_nodes(&nodes, 0, 1);
4142
4143         let our_payment_hash = if send_partial_mpp {
4144                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4145                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4146                 // indicates there are more HTLCs coming.
4147                 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.
4148                 let payment_id = PaymentId([42; 32]);
4149                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4150                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4151                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4152                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4153                         &None, session_privs[0]).unwrap();
4154                 check_added_monitors!(nodes[0], 1);
4155                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4156                 assert_eq!(events.len(), 1);
4157                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4158                 // hop should *not* yet generate any PaymentClaimable event(s).
4159                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4160                 our_payment_hash
4161         } else {
4162                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4163         };
4164
4165         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4166         connect_block(&nodes[0], &block);
4167         connect_block(&nodes[1], &block);
4168         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4169         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4170                 block.header.prev_blockhash = block.block_hash();
4171                 connect_block(&nodes[0], &block);
4172                 connect_block(&nodes[1], &block);
4173         }
4174
4175         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4176
4177         check_added_monitors!(nodes[1], 1);
4178         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4179         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4180         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4181         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4182         assert!(htlc_timeout_updates.update_fee.is_none());
4183
4184         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4185         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4186         // 100_000 msat as u64, followed by the height at which we failed back above
4187         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4188         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4189         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4190 }
4191
4192 #[test]
4193 fn test_htlc_timeout() {
4194         do_test_htlc_timeout(true);
4195         do_test_htlc_timeout(false);
4196 }
4197
4198 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4199         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4200         let chanmon_cfgs = create_chanmon_cfgs(3);
4201         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4202         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4203         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4204         create_announced_chan_between_nodes(&nodes, 0, 1);
4205         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4206
4207         // Make sure all nodes are at the same starting height
4208         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4209         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4210         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4211
4212         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4213         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4214         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4215                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4216         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4217         check_added_monitors!(nodes[1], 1);
4218
4219         // Now attempt to route a second payment, which should be placed in the holding cell
4220         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4221         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4222         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4223                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4224         if forwarded_htlc {
4225                 check_added_monitors!(nodes[0], 1);
4226                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4227                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4228                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4229                 expect_pending_htlcs_forwardable!(nodes[1]);
4230         }
4231         check_added_monitors!(nodes[1], 0);
4232
4233         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4234         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4235         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4236         connect_blocks(&nodes[1], 1);
4237
4238         if forwarded_htlc {
4239                 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 }]);
4240                 check_added_monitors!(nodes[1], 1);
4241                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4242                 assert_eq!(fail_commit.len(), 1);
4243                 match fail_commit[0] {
4244                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4245                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4246                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4247                         },
4248                         _ => unreachable!(),
4249                 }
4250                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4251         } else {
4252                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4253         }
4254 }
4255
4256 #[test]
4257 fn test_holding_cell_htlc_add_timeouts() {
4258         do_test_holding_cell_htlc_add_timeouts(false);
4259         do_test_holding_cell_htlc_add_timeouts(true);
4260 }
4261
4262 macro_rules! check_spendable_outputs {
4263         ($node: expr, $keysinterface: expr) => {
4264                 {
4265                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4266                         let mut txn = Vec::new();
4267                         let mut all_outputs = Vec::new();
4268                         let secp_ctx = Secp256k1::new();
4269                         for event in events.drain(..) {
4270                                 match event {
4271                                         Event::SpendableOutputs { mut outputs } => {
4272                                                 for outp in outputs.drain(..) {
4273                                                         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());
4274                                                         all_outputs.push(outp);
4275                                                 }
4276                                         },
4277                                         _ => panic!("Unexpected event"),
4278                                 };
4279                         }
4280                         if all_outputs.len() > 1 {
4281                                 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) {
4282                                         txn.push(tx);
4283                                 }
4284                         }
4285                         txn
4286                 }
4287         }
4288 }
4289
4290 #[test]
4291 fn test_claim_sizeable_push_msat() {
4292         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4293         let chanmon_cfgs = create_chanmon_cfgs(2);
4294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4297
4298         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4299         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4300         check_closed_broadcast!(nodes[1], true);
4301         check_added_monitors!(nodes[1], 1);
4302         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4303         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4304         assert_eq!(node_txn.len(), 1);
4305         check_spends!(node_txn[0], chan.3);
4306         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
4307
4308         mine_transaction(&nodes[1], &node_txn[0]);
4309         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4310
4311         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4312         assert_eq!(spend_txn.len(), 1);
4313         assert_eq!(spend_txn[0].input.len(), 1);
4314         check_spends!(spend_txn[0], node_txn[0]);
4315         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4316 }
4317
4318 #[test]
4319 fn test_claim_on_remote_sizeable_push_msat() {
4320         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4321         // to_remote output is encumbered by a P2WPKH
4322         let chanmon_cfgs = create_chanmon_cfgs(2);
4323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4325         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4326
4327         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4328         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4329         check_closed_broadcast!(nodes[0], true);
4330         check_added_monitors!(nodes[0], 1);
4331         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4332
4333         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4334         assert_eq!(node_txn.len(), 1);
4335         check_spends!(node_txn[0], chan.3);
4336         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
4337
4338         mine_transaction(&nodes[1], &node_txn[0]);
4339         check_closed_broadcast!(nodes[1], true);
4340         check_added_monitors!(nodes[1], 1);
4341         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4342         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4343
4344         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4345         assert_eq!(spend_txn.len(), 1);
4346         check_spends!(spend_txn[0], node_txn[0]);
4347 }
4348
4349 #[test]
4350 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4351         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4352         // to_remote output is encumbered by a P2WPKH
4353
4354         let chanmon_cfgs = create_chanmon_cfgs(2);
4355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4357         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4358
4359         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4360         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4361         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4362         assert_eq!(revoked_local_txn[0].input.len(), 1);
4363         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4364
4365         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4366         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4367         check_closed_broadcast!(nodes[1], true);
4368         check_added_monitors!(nodes[1], 1);
4369         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4370
4371         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4372         mine_transaction(&nodes[1], &node_txn[0]);
4373         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4374
4375         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4376         assert_eq!(spend_txn.len(), 3);
4377         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4378         check_spends!(spend_txn[1], node_txn[0]);
4379         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4380 }
4381
4382 #[test]
4383 fn test_static_spendable_outputs_preimage_tx() {
4384         let chanmon_cfgs = create_chanmon_cfgs(2);
4385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4387         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4388
4389         // Create some initial channels
4390         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4391
4392         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4393
4394         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4395         assert_eq!(commitment_tx[0].input.len(), 1);
4396         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4397
4398         // Settle A's commitment tx on B's chain
4399         nodes[1].node.claim_funds(payment_preimage);
4400         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4401         check_added_monitors!(nodes[1], 1);
4402         mine_transaction(&nodes[1], &commitment_tx[0]);
4403         check_added_monitors!(nodes[1], 1);
4404         let events = nodes[1].node.get_and_clear_pending_msg_events();
4405         match events[0] {
4406                 MessageSendEvent::UpdateHTLCs { .. } => {},
4407                 _ => panic!("Unexpected event"),
4408         }
4409         match events[1] {
4410                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4411                 _ => panic!("Unexepected event"),
4412         }
4413
4414         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4415         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4416         assert_eq!(node_txn.len(), 1);
4417         check_spends!(node_txn[0], commitment_tx[0]);
4418         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4419
4420         mine_transaction(&nodes[1], &node_txn[0]);
4421         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4422         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4423
4424         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4425         assert_eq!(spend_txn.len(), 1);
4426         check_spends!(spend_txn[0], node_txn[0]);
4427 }
4428
4429 #[test]
4430 fn test_static_spendable_outputs_timeout_tx() {
4431         let chanmon_cfgs = create_chanmon_cfgs(2);
4432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4434         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4435
4436         // Create some initial channels
4437         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4438
4439         // Rebalance the network a bit by relaying one payment through all the channels ...
4440         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4441
4442         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4443
4444         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4445         assert_eq!(commitment_tx[0].input.len(), 1);
4446         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4447
4448         // Settle A's commitment tx on B' chain
4449         mine_transaction(&nodes[1], &commitment_tx[0]);
4450         check_added_monitors!(nodes[1], 1);
4451         let events = nodes[1].node.get_and_clear_pending_msg_events();
4452         match events[0] {
4453                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4454                 _ => panic!("Unexpected event"),
4455         }
4456         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4457
4458         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4459         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4460         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4461         check_spends!(node_txn[0],  commitment_tx[0].clone());
4462         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4463
4464         mine_transaction(&nodes[1], &node_txn[0]);
4465         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4466         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4467         expect_payment_failed!(nodes[1], our_payment_hash, false);
4468
4469         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4470         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4471         check_spends!(spend_txn[0], commitment_tx[0]);
4472         check_spends!(spend_txn[1], node_txn[0]);
4473         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4474 }
4475
4476 #[test]
4477 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4478         let chanmon_cfgs = create_chanmon_cfgs(2);
4479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4481         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4482
4483         // Create some initial channels
4484         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4485
4486         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4487         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4488         assert_eq!(revoked_local_txn[0].input.len(), 1);
4489         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4490
4491         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4492
4493         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4494         check_closed_broadcast!(nodes[1], true);
4495         check_added_monitors!(nodes[1], 1);
4496         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4497
4498         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4499         assert_eq!(node_txn.len(), 1);
4500         assert_eq!(node_txn[0].input.len(), 2);
4501         check_spends!(node_txn[0], revoked_local_txn[0]);
4502
4503         mine_transaction(&nodes[1], &node_txn[0]);
4504         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4505
4506         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4507         assert_eq!(spend_txn.len(), 1);
4508         check_spends!(spend_txn[0], node_txn[0]);
4509 }
4510
4511 #[test]
4512 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4513         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4514         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4517         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4518
4519         // Create some initial channels
4520         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4521
4522         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4523         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4524         assert_eq!(revoked_local_txn[0].input.len(), 1);
4525         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4526
4527         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4528
4529         // A will generate HTLC-Timeout from revoked commitment tx
4530         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4531         check_closed_broadcast!(nodes[0], true);
4532         check_added_monitors!(nodes[0], 1);
4533         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4534         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4535
4536         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4537         assert_eq!(revoked_htlc_txn.len(), 1);
4538         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4539         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4540         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4541         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4542
4543         // B will generate justice tx from A's revoked commitment/HTLC tx
4544         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4545         check_closed_broadcast!(nodes[1], true);
4546         check_added_monitors!(nodes[1], 1);
4547         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4548
4549         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4550         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4551         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4552         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4553         // transactions next...
4554         assert_eq!(node_txn[0].input.len(), 3);
4555         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4556
4557         assert_eq!(node_txn[1].input.len(), 2);
4558         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4559         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4560                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4561         } else {
4562                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4563                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4564         }
4565
4566         mine_transaction(&nodes[1], &node_txn[1]);
4567         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4568
4569         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4570         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4571         assert_eq!(spend_txn.len(), 1);
4572         assert_eq!(spend_txn[0].input.len(), 1);
4573         check_spends!(spend_txn[0], node_txn[1]);
4574 }
4575
4576 #[test]
4577 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4578         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4579         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4582         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4583
4584         // Create some initial channels
4585         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4586
4587         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4588         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4589         assert_eq!(revoked_local_txn[0].input.len(), 1);
4590         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4591
4592         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4593         assert_eq!(revoked_local_txn[0].output.len(), 2);
4594
4595         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4596
4597         // B will generate HTLC-Success from revoked commitment tx
4598         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4599         check_closed_broadcast!(nodes[1], true);
4600         check_added_monitors!(nodes[1], 1);
4601         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4602         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4603
4604         assert_eq!(revoked_htlc_txn.len(), 1);
4605         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4606         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4607         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4608
4609         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4610         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4611         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4612
4613         // A will generate justice tx from B's revoked commitment/HTLC tx
4614         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4615         check_closed_broadcast!(nodes[0], true);
4616         check_added_monitors!(nodes[0], 1);
4617         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4618
4619         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4620         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4621
4622         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4623         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4624         // transactions next...
4625         assert_eq!(node_txn[0].input.len(), 2);
4626         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4627         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4628                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4629         } else {
4630                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4631                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4632         }
4633
4634         assert_eq!(node_txn[1].input.len(), 1);
4635         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4636
4637         mine_transaction(&nodes[0], &node_txn[1]);
4638         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4639
4640         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4641         // didn't try to generate any new transactions.
4642
4643         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4644         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4645         assert_eq!(spend_txn.len(), 3);
4646         assert_eq!(spend_txn[0].input.len(), 1);
4647         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4648         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4649         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4650         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4651 }
4652
4653 #[test]
4654 fn test_onchain_to_onchain_claim() {
4655         // Test that in case of channel closure, we detect the state of output and claim HTLC
4656         // on downstream peer's remote commitment tx.
4657         // First, have C claim an HTLC against its own latest commitment transaction.
4658         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4659         // channel.
4660         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4661         // gets broadcast.
4662
4663         let chanmon_cfgs = create_chanmon_cfgs(3);
4664         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4665         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4666         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4667
4668         // Create some initial channels
4669         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4670         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4671
4672         // Ensure all nodes are at the same height
4673         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4674         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4675         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4676         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4677
4678         // Rebalance the network a bit by relaying one payment through all the channels ...
4679         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4680         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4681
4682         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4683         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4684         check_spends!(commitment_tx[0], chan_2.3);
4685         nodes[2].node.claim_funds(payment_preimage);
4686         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4687         check_added_monitors!(nodes[2], 1);
4688         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4689         assert!(updates.update_add_htlcs.is_empty());
4690         assert!(updates.update_fail_htlcs.is_empty());
4691         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4692         assert!(updates.update_fail_malformed_htlcs.is_empty());
4693
4694         mine_transaction(&nodes[2], &commitment_tx[0]);
4695         check_closed_broadcast!(nodes[2], true);
4696         check_added_monitors!(nodes[2], 1);
4697         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4698
4699         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4700         assert_eq!(c_txn.len(), 1);
4701         check_spends!(c_txn[0], commitment_tx[0]);
4702         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4703         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4704         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4705
4706         // 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
4707         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4708         check_added_monitors!(nodes[1], 1);
4709         let events = nodes[1].node.get_and_clear_pending_events();
4710         assert_eq!(events.len(), 2);
4711         match events[0] {
4712                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4713                 _ => panic!("Unexpected event"),
4714         }
4715         match events[1] {
4716                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4717                         assert_eq!(fee_earned_msat, Some(1000));
4718                         assert_eq!(prev_channel_id, Some(chan_1.2));
4719                         assert_eq!(claim_from_onchain_tx, true);
4720                         assert_eq!(next_channel_id, Some(chan_2.2));
4721                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4722                 },
4723                 _ => panic!("Unexpected event"),
4724         }
4725         check_added_monitors!(nodes[1], 1);
4726         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4727         assert_eq!(msg_events.len(), 3);
4728         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4729         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4730
4731         match nodes_2_event {
4732                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4733                 _ => panic!("Unexpected event"),
4734         }
4735
4736         match nodes_0_event {
4737                 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, .. } } => {
4738                         assert!(update_add_htlcs.is_empty());
4739                         assert!(update_fail_htlcs.is_empty());
4740                         assert_eq!(update_fulfill_htlcs.len(), 1);
4741                         assert!(update_fail_malformed_htlcs.is_empty());
4742                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4743                 },
4744                 _ => panic!("Unexpected event"),
4745         };
4746
4747         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4748         match msg_events[0] {
4749                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4750                 _ => panic!("Unexpected event"),
4751         }
4752
4753         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4754         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4755         mine_transaction(&nodes[1], &commitment_tx[0]);
4756         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4757         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4758         // ChannelMonitor: HTLC-Success tx
4759         assert_eq!(b_txn.len(), 1);
4760         check_spends!(b_txn[0], commitment_tx[0]);
4761         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4762         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4763         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4764
4765         check_closed_broadcast!(nodes[1], true);
4766         check_added_monitors!(nodes[1], 1);
4767 }
4768
4769 #[test]
4770 fn test_duplicate_payment_hash_one_failure_one_success() {
4771         // Topology : A --> B --> C --> D
4772         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4773         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4774         // we forward one of the payments onwards to D.
4775         let chanmon_cfgs = create_chanmon_cfgs(4);
4776         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4777         // When this test was written, the default base fee floated based on the HTLC count.
4778         // It is now fixed, so we simply set the fee to the expected value here.
4779         let mut config = test_default_channel_config();
4780         config.channel_config.forwarding_fee_base_msat = 196;
4781         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4782                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4783         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4784
4785         create_announced_chan_between_nodes(&nodes, 0, 1);
4786         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4787         create_announced_chan_between_nodes(&nodes, 2, 3);
4788
4789         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4790         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4791         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4792         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4793         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4794
4795         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4796
4797         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4798         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4799         // script push size limit so that the below script length checks match
4800         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4801         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4802                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4803         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4804         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4805
4806         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4807         assert_eq!(commitment_txn[0].input.len(), 1);
4808         check_spends!(commitment_txn[0], chan_2.3);
4809
4810         mine_transaction(&nodes[1], &commitment_txn[0]);
4811         check_closed_broadcast!(nodes[1], true);
4812         check_added_monitors!(nodes[1], 1);
4813         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4814         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4815
4816         let htlc_timeout_tx;
4817         { // Extract one of the two HTLC-Timeout transaction
4818                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4819                 // ChannelMonitor: timeout tx * 2-or-3
4820                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4821
4822                 check_spends!(node_txn[0], commitment_txn[0]);
4823                 assert_eq!(node_txn[0].input.len(), 1);
4824                 assert_eq!(node_txn[0].output.len(), 1);
4825
4826                 if node_txn.len() > 2 {
4827                         check_spends!(node_txn[1], commitment_txn[0]);
4828                         assert_eq!(node_txn[1].input.len(), 1);
4829                         assert_eq!(node_txn[1].output.len(), 1);
4830                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4831
4832                         check_spends!(node_txn[2], commitment_txn[0]);
4833                         assert_eq!(node_txn[2].input.len(), 1);
4834                         assert_eq!(node_txn[2].output.len(), 1);
4835                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4836                 } else {
4837                         check_spends!(node_txn[1], commitment_txn[0]);
4838                         assert_eq!(node_txn[1].input.len(), 1);
4839                         assert_eq!(node_txn[1].output.len(), 1);
4840                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4841                 }
4842
4843                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4844                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4845                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4846                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4847                 if node_txn.len() > 2 {
4848                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4849                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4850                 } else {
4851                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4852                 }
4853         }
4854
4855         nodes[2].node.claim_funds(our_payment_preimage);
4856         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4857
4858         mine_transaction(&nodes[2], &commitment_txn[0]);
4859         check_added_monitors!(nodes[2], 2);
4860         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4861         let events = nodes[2].node.get_and_clear_pending_msg_events();
4862         match events[0] {
4863                 MessageSendEvent::UpdateHTLCs { .. } => {},
4864                 _ => panic!("Unexpected event"),
4865         }
4866         match events[1] {
4867                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4868                 _ => panic!("Unexepected event"),
4869         }
4870         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4871         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4872         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4873         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4874         assert_eq!(htlc_success_txn[0].input.len(), 1);
4875         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4876         assert_eq!(htlc_success_txn[1].input.len(), 1);
4877         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4878         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4879         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4880
4881         mine_transaction(&nodes[1], &htlc_timeout_tx);
4882         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4883         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 }]);
4884         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4885         assert!(htlc_updates.update_add_htlcs.is_empty());
4886         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4887         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4888         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4889         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4890         check_added_monitors!(nodes[1], 1);
4891
4892         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4893         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4894         {
4895                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4896         }
4897         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4898
4899         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4900         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4901         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4902         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4903         assert!(updates.update_add_htlcs.is_empty());
4904         assert!(updates.update_fail_htlcs.is_empty());
4905         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4906         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4907         assert!(updates.update_fail_malformed_htlcs.is_empty());
4908         check_added_monitors!(nodes[1], 1);
4909
4910         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4911         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4912         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4913 }
4914
4915 #[test]
4916 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4917         let chanmon_cfgs = create_chanmon_cfgs(2);
4918         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4919         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4920         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4921
4922         // Create some initial channels
4923         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4924
4925         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4926         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4927         assert_eq!(local_txn.len(), 1);
4928         assert_eq!(local_txn[0].input.len(), 1);
4929         check_spends!(local_txn[0], chan_1.3);
4930
4931         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4932         nodes[1].node.claim_funds(payment_preimage);
4933         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4934         check_added_monitors!(nodes[1], 1);
4935
4936         mine_transaction(&nodes[1], &local_txn[0]);
4937         check_added_monitors!(nodes[1], 1);
4938         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4939         let events = nodes[1].node.get_and_clear_pending_msg_events();
4940         match events[0] {
4941                 MessageSendEvent::UpdateHTLCs { .. } => {},
4942                 _ => panic!("Unexpected event"),
4943         }
4944         match events[1] {
4945                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4946                 _ => panic!("Unexepected event"),
4947         }
4948         let node_tx = {
4949                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4950                 assert_eq!(node_txn.len(), 1);
4951                 assert_eq!(node_txn[0].input.len(), 1);
4952                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4953                 check_spends!(node_txn[0], local_txn[0]);
4954                 node_txn[0].clone()
4955         };
4956
4957         mine_transaction(&nodes[1], &node_tx);
4958         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4959
4960         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4961         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4962         assert_eq!(spend_txn.len(), 1);
4963         assert_eq!(spend_txn[0].input.len(), 1);
4964         check_spends!(spend_txn[0], node_tx);
4965         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4966 }
4967
4968 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4969         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4970         // unrevoked commitment transaction.
4971         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4972         // a remote RAA before they could be failed backwards (and combinations thereof).
4973         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4974         // use the same payment hashes.
4975         // Thus, we use a six-node network:
4976         //
4977         // A \         / E
4978         //    - C - D -
4979         // B /         \ F
4980         // And test where C fails back to A/B when D announces its latest commitment transaction
4981         let chanmon_cfgs = create_chanmon_cfgs(6);
4982         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4983         // When this test was written, the default base fee floated based on the HTLC count.
4984         // It is now fixed, so we simply set the fee to the expected value here.
4985         let mut config = test_default_channel_config();
4986         config.channel_config.forwarding_fee_base_msat = 196;
4987         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4988                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4989         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4990
4991         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4992         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4993         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4994         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4995         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4996
4997         // Rebalance and check output sanity...
4998         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4999         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5000         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5001
5002         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5003                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5004         // 0th HTLC:
5005         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
5006         // 1st HTLC:
5007         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
5008         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5009         // 2nd HTLC:
5010         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
5011         // 3rd HTLC:
5012         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
5013         // 4th HTLC:
5014         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5015         // 5th HTLC:
5016         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5017         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5018         // 6th HTLC:
5019         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());
5020         // 7th HTLC:
5021         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());
5022
5023         // 8th HTLC:
5024         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5025         // 9th HTLC:
5026         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5027         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
5028
5029         // 10th HTLC:
5030         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
5031         // 11th HTLC:
5032         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5033         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());
5034
5035         // Double-check that six of the new HTLC were added
5036         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5037         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5038         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5039         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5040
5041         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5042         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5043         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5044         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5045         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5046         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5047         check_added_monitors!(nodes[4], 0);
5048
5049         let failed_destinations = vec![
5050                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5051                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5052                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5053                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5054         ];
5055         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5056         check_added_monitors!(nodes[4], 1);
5057
5058         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5059         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5060         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5061         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5062         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5063         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5064
5065         // Fail 3rd below-dust and 7th above-dust HTLCs
5066         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5067         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5068         check_added_monitors!(nodes[5], 0);
5069
5070         let failed_destinations_2 = vec![
5071                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5072                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5073         ];
5074         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5075         check_added_monitors!(nodes[5], 1);
5076
5077         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5078         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5079         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5080         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5081
5082         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5083
5084         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5085         let failed_destinations_3 = vec![
5086                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5087                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5088                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5089                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5090                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5091                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5092         ];
5093         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5094         check_added_monitors!(nodes[3], 1);
5095         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5096         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5097         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5098         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5099         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5100         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5101         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5102         if deliver_last_raa {
5103                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5104         } else {
5105                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5106         }
5107
5108         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5109         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5110         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5111         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5112         //
5113         // We now broadcast the latest commitment transaction, which *should* result in failures for
5114         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5115         // the non-broadcast above-dust HTLCs.
5116         //
5117         // Alternatively, we may broadcast the previous commitment transaction, which should only
5118         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5119         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5120
5121         if announce_latest {
5122                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5123         } else {
5124                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5125         }
5126         let events = nodes[2].node.get_and_clear_pending_events();
5127         let close_event = if deliver_last_raa {
5128                 assert_eq!(events.len(), 2 + 6);
5129                 events.last().clone().unwrap()
5130         } else {
5131                 assert_eq!(events.len(), 1);
5132                 events.last().clone().unwrap()
5133         };
5134         match close_event {
5135                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5136                 _ => panic!("Unexpected event"),
5137         }
5138
5139         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5140         check_closed_broadcast!(nodes[2], true);
5141         if deliver_last_raa {
5142                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5143
5144                 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();
5145                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5146         } else {
5147                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5148                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5149                 } else {
5150                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5151                 };
5152
5153                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5154         }
5155         check_added_monitors!(nodes[2], 3);
5156
5157         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5158         assert_eq!(cs_msgs.len(), 2);
5159         let mut a_done = false;
5160         for msg in cs_msgs {
5161                 match msg {
5162                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5163                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5164                                 // should be failed-backwards here.
5165                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5166                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5167                                         for htlc in &updates.update_fail_htlcs {
5168                                                 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 });
5169                                         }
5170                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5171                                         assert!(!a_done);
5172                                         a_done = true;
5173                                         &nodes[0]
5174                                 } else {
5175                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5176                                         for htlc in &updates.update_fail_htlcs {
5177                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5178                                         }
5179                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5180                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5181                                         &nodes[1]
5182                                 };
5183                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5184                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5185                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5186                                 if announce_latest {
5187                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5188                                         if *node_id == nodes[0].node.get_our_node_id() {
5189                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5190                                         }
5191                                 }
5192                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5193                         },
5194                         _ => panic!("Unexpected event"),
5195                 }
5196         }
5197
5198         let as_events = nodes[0].node.get_and_clear_pending_events();
5199         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5200         let mut as_failds = HashSet::new();
5201         let mut as_updates = 0;
5202         for event in as_events.iter() {
5203                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5204                         assert!(as_failds.insert(*payment_hash));
5205                         if *payment_hash != payment_hash_2 {
5206                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5207                         } else {
5208                                 assert!(!payment_failed_permanently);
5209                         }
5210                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5211                                 as_updates += 1;
5212                         }
5213                 } else if let &Event::PaymentFailed { .. } = event {
5214                 } else { panic!("Unexpected event"); }
5215         }
5216         assert!(as_failds.contains(&payment_hash_1));
5217         assert!(as_failds.contains(&payment_hash_2));
5218         if announce_latest {
5219                 assert!(as_failds.contains(&payment_hash_3));
5220                 assert!(as_failds.contains(&payment_hash_5));
5221         }
5222         assert!(as_failds.contains(&payment_hash_6));
5223
5224         let bs_events = nodes[1].node.get_and_clear_pending_events();
5225         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5226         let mut bs_failds = HashSet::new();
5227         let mut bs_updates = 0;
5228         for event in bs_events.iter() {
5229                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5230                         assert!(bs_failds.insert(*payment_hash));
5231                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5232                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5233                         } else {
5234                                 assert!(!payment_failed_permanently);
5235                         }
5236                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5237                                 bs_updates += 1;
5238                         }
5239                 } else if let &Event::PaymentFailed { .. } = event {
5240                 } else { panic!("Unexpected event"); }
5241         }
5242         assert!(bs_failds.contains(&payment_hash_1));
5243         assert!(bs_failds.contains(&payment_hash_2));
5244         if announce_latest {
5245                 assert!(bs_failds.contains(&payment_hash_4));
5246         }
5247         assert!(bs_failds.contains(&payment_hash_5));
5248
5249         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5250         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5251         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5252         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5253         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5254         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5255 }
5256
5257 #[test]
5258 fn test_fail_backwards_latest_remote_announce_a() {
5259         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5260 }
5261
5262 #[test]
5263 fn test_fail_backwards_latest_remote_announce_b() {
5264         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5265 }
5266
5267 #[test]
5268 fn test_fail_backwards_previous_remote_announce() {
5269         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5270         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5271         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5272 }
5273
5274 #[test]
5275 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5276         let chanmon_cfgs = create_chanmon_cfgs(2);
5277         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5278         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5279         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5280
5281         // Create some initial channels
5282         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5283
5284         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5285         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5286         assert_eq!(local_txn[0].input.len(), 1);
5287         check_spends!(local_txn[0], chan_1.3);
5288
5289         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5290         mine_transaction(&nodes[0], &local_txn[0]);
5291         check_closed_broadcast!(nodes[0], true);
5292         check_added_monitors!(nodes[0], 1);
5293         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5294         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5295
5296         let htlc_timeout = {
5297                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5298                 assert_eq!(node_txn.len(), 1);
5299                 assert_eq!(node_txn[0].input.len(), 1);
5300                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5301                 check_spends!(node_txn[0], local_txn[0]);
5302                 node_txn[0].clone()
5303         };
5304
5305         mine_transaction(&nodes[0], &htlc_timeout);
5306         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5307         expect_payment_failed!(nodes[0], our_payment_hash, false);
5308
5309         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5310         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5311         assert_eq!(spend_txn.len(), 3);
5312         check_spends!(spend_txn[0], local_txn[0]);
5313         assert_eq!(spend_txn[1].input.len(), 1);
5314         check_spends!(spend_txn[1], htlc_timeout);
5315         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5316         assert_eq!(spend_txn[2].input.len(), 2);
5317         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5318         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5319                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5320 }
5321
5322 #[test]
5323 fn test_key_derivation_params() {
5324         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5325         // manager rotation to test that `channel_keys_id` returned in
5326         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5327         // then derive a `delayed_payment_key`.
5328
5329         let chanmon_cfgs = create_chanmon_cfgs(3);
5330
5331         // We manually create the node configuration to backup the seed.
5332         let seed = [42; 32];
5333         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5334         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);
5335         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5336         let scorer = Mutex::new(test_utils::TestScorer::new());
5337         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5338         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)) };
5339         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5340         node_cfgs.remove(0);
5341         node_cfgs.insert(0, node);
5342
5343         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5344         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5345
5346         // Create some initial channels
5347         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5348         // for node 0
5349         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5350         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5351         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5352
5353         // Ensure all nodes are at the same height
5354         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5355         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5356         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5357         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5358
5359         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5360         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5361         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5362         assert_eq!(local_txn_1[0].input.len(), 1);
5363         check_spends!(local_txn_1[0], chan_1.3);
5364
5365         // We check funding pubkey are unique
5366         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]));
5367         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]));
5368         if from_0_funding_key_0 == from_1_funding_key_0
5369             || from_0_funding_key_0 == from_1_funding_key_1
5370             || from_0_funding_key_1 == from_1_funding_key_0
5371             || from_0_funding_key_1 == from_1_funding_key_1 {
5372                 panic!("Funding pubkeys aren't unique");
5373         }
5374
5375         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5376         mine_transaction(&nodes[0], &local_txn_1[0]);
5377         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5378         check_closed_broadcast!(nodes[0], true);
5379         check_added_monitors!(nodes[0], 1);
5380         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5381
5382         let htlc_timeout = {
5383                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5384                 assert_eq!(node_txn.len(), 1);
5385                 assert_eq!(node_txn[0].input.len(), 1);
5386                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5387                 check_spends!(node_txn[0], local_txn_1[0]);
5388                 node_txn[0].clone()
5389         };
5390
5391         mine_transaction(&nodes[0], &htlc_timeout);
5392         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5393         expect_payment_failed!(nodes[0], our_payment_hash, false);
5394
5395         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5396         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5397         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5398         assert_eq!(spend_txn.len(), 3);
5399         check_spends!(spend_txn[0], local_txn_1[0]);
5400         assert_eq!(spend_txn[1].input.len(), 1);
5401         check_spends!(spend_txn[1], htlc_timeout);
5402         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5403         assert_eq!(spend_txn[2].input.len(), 2);
5404         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5405         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5406                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5407 }
5408
5409 #[test]
5410 fn test_static_output_closing_tx() {
5411         let chanmon_cfgs = create_chanmon_cfgs(2);
5412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5414         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5415
5416         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5417
5418         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5419         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5420
5421         mine_transaction(&nodes[0], &closing_tx);
5422         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5423         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5424
5425         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5426         assert_eq!(spend_txn.len(), 1);
5427         check_spends!(spend_txn[0], closing_tx);
5428
5429         mine_transaction(&nodes[1], &closing_tx);
5430         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5431         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5432
5433         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5434         assert_eq!(spend_txn.len(), 1);
5435         check_spends!(spend_txn[0], closing_tx);
5436 }
5437
5438 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5439         let chanmon_cfgs = create_chanmon_cfgs(2);
5440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5442         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5443         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5444
5445         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5446
5447         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5448         // present in B's local commitment transaction, but none of A's commitment transactions.
5449         nodes[1].node.claim_funds(payment_preimage);
5450         check_added_monitors!(nodes[1], 1);
5451         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5452
5453         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5454         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5455         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5456
5457         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5458         check_added_monitors!(nodes[0], 1);
5459         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5460         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5461         check_added_monitors!(nodes[1], 1);
5462
5463         let starting_block = nodes[1].best_block_info();
5464         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5465         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5466                 connect_block(&nodes[1], &block);
5467                 block.header.prev_blockhash = block.block_hash();
5468         }
5469         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5470         check_closed_broadcast!(nodes[1], true);
5471         check_added_monitors!(nodes[1], 1);
5472         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5473 }
5474
5475 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5476         let chanmon_cfgs = create_chanmon_cfgs(2);
5477         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5478         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5479         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5480         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5481
5482         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5483         nodes[0].node.send_payment_with_route(&route, payment_hash,
5484                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5485         check_added_monitors!(nodes[0], 1);
5486
5487         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5488
5489         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5490         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5491         // to "time out" the HTLC.
5492
5493         let starting_block = nodes[1].best_block_info();
5494         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5495
5496         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5497                 connect_block(&nodes[0], &block);
5498                 block.header.prev_blockhash = block.block_hash();
5499         }
5500         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5501         check_closed_broadcast!(nodes[0], true);
5502         check_added_monitors!(nodes[0], 1);
5503         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5504 }
5505
5506 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5507         let chanmon_cfgs = create_chanmon_cfgs(3);
5508         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5509         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5510         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5511         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5512
5513         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5514         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5515         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5516         // actually revoked.
5517         let htlc_value = if use_dust { 50000 } else { 3000000 };
5518         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5519         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5520         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5521         check_added_monitors!(nodes[1], 1);
5522
5523         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5524         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5525         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5526         check_added_monitors!(nodes[0], 1);
5527         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5528         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5529         check_added_monitors!(nodes[1], 1);
5530         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5531         check_added_monitors!(nodes[1], 1);
5532         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5533
5534         if check_revoke_no_close {
5535                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5536                 check_added_monitors!(nodes[0], 1);
5537         }
5538
5539         let starting_block = nodes[1].best_block_info();
5540         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5541         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5542                 connect_block(&nodes[0], &block);
5543                 block.header.prev_blockhash = block.block_hash();
5544         }
5545         if !check_revoke_no_close {
5546                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5547                 check_closed_broadcast!(nodes[0], true);
5548                 check_added_monitors!(nodes[0], 1);
5549                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5550         } else {
5551                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5552         }
5553 }
5554
5555 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5556 // There are only a few cases to test here:
5557 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5558 //    broadcastable commitment transactions result in channel closure,
5559 //  * its included in an unrevoked-but-previous remote commitment transaction,
5560 //  * its included in the latest remote or local commitment transactions.
5561 // We test each of the three possible commitment transactions individually and use both dust and
5562 // non-dust HTLCs.
5563 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5564 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5565 // tested for at least one of the cases in other tests.
5566 #[test]
5567 fn htlc_claim_single_commitment_only_a() {
5568         do_htlc_claim_local_commitment_only(true);
5569         do_htlc_claim_local_commitment_only(false);
5570
5571         do_htlc_claim_current_remote_commitment_only(true);
5572         do_htlc_claim_current_remote_commitment_only(false);
5573 }
5574
5575 #[test]
5576 fn htlc_claim_single_commitment_only_b() {
5577         do_htlc_claim_previous_remote_commitment_only(true, false);
5578         do_htlc_claim_previous_remote_commitment_only(false, false);
5579         do_htlc_claim_previous_remote_commitment_only(true, true);
5580         do_htlc_claim_previous_remote_commitment_only(false, true);
5581 }
5582
5583 #[test]
5584 #[should_panic]
5585 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5586         let chanmon_cfgs = create_chanmon_cfgs(2);
5587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5589         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5590         // Force duplicate randomness for every get-random call
5591         for node in nodes.iter() {
5592                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5593         }
5594
5595         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5596         let channel_value_satoshis=10000;
5597         let push_msat=10001;
5598         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5599         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5600         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5601         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5602
5603         // Create a second channel with the same random values. This used to panic due to a colliding
5604         // channel_id, but now panics due to a colliding outbound SCID alias.
5605         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5606 }
5607
5608 #[test]
5609 fn bolt2_open_channel_sending_node_checks_part2() {
5610         let chanmon_cfgs = create_chanmon_cfgs(2);
5611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5613         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5614
5615         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5616         let channel_value_satoshis=2^24;
5617         let push_msat=10001;
5618         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5619
5620         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5621         let channel_value_satoshis=10000;
5622         // Test when push_msat is equal to 1000 * funding_satoshis.
5623         let push_msat=1000*channel_value_satoshis+1;
5624         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5625
5626         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5627         let channel_value_satoshis=10000;
5628         let push_msat=10001;
5629         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
5630         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5631         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5632
5633         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5634         // 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
5635         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5636
5637         // 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.
5638         assert!(BREAKDOWN_TIMEOUT>0);
5639         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5640
5641         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5642         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5643         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5644
5645         // 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.
5646         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5647         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5648         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5649         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5650         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5651 }
5652
5653 #[test]
5654 fn bolt2_open_channel_sane_dust_limit() {
5655         let chanmon_cfgs = create_chanmon_cfgs(2);
5656         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5657         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5658         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5659
5660         let channel_value_satoshis=1000000;
5661         let push_msat=10001;
5662         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5663         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5664         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5665         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5666
5667         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5668         let events = nodes[1].node.get_and_clear_pending_msg_events();
5669         let err_msg = match events[0] {
5670                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5671                         msg.clone()
5672                 },
5673                 _ => panic!("Unexpected event"),
5674         };
5675         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5676 }
5677
5678 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5679 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5680 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5681 // is no longer affordable once it's freed.
5682 #[test]
5683 fn test_fail_holding_cell_htlc_upon_free() {
5684         let chanmon_cfgs = create_chanmon_cfgs(2);
5685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5687         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5688         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5689
5690         // First nodes[0] generates an update_fee, setting the channel's
5691         // pending_update_fee.
5692         {
5693                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5694                 *feerate_lock += 20;
5695         }
5696         nodes[0].node.timer_tick_occurred();
5697         check_added_monitors!(nodes[0], 1);
5698
5699         let events = nodes[0].node.get_and_clear_pending_msg_events();
5700         assert_eq!(events.len(), 1);
5701         let (update_msg, commitment_signed) = match events[0] {
5702                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5703                         (update_fee.as_ref(), commitment_signed)
5704                 },
5705                 _ => panic!("Unexpected event"),
5706         };
5707
5708         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5709
5710         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5711         let channel_reserve = chan_stat.channel_reserve_msat;
5712         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5713         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5714
5715         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5716         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5717         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5718
5719         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5720         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5721                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5722         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5723         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5724
5725         // Flush the pending fee update.
5726         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5727         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5728         check_added_monitors!(nodes[1], 1);
5729         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5730         check_added_monitors!(nodes[0], 1);
5731
5732         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5733         // HTLC, but now that the fee has been raised the payment will now fail, causing
5734         // us to surface its failure to the user.
5735         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5736         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5737         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);
5738
5739         // Check that the payment failed to be sent out.
5740         let events = nodes[0].node.get_and_clear_pending_events();
5741         assert_eq!(events.len(), 2);
5742         match &events[0] {
5743                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5744                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5745                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5746                         assert_eq!(*payment_failed_permanently, false);
5747                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5748                 },
5749                 _ => panic!("Unexpected event"),
5750         }
5751         match &events[1] {
5752                 &Event::PaymentFailed { ref payment_hash, .. } => {
5753                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5754                 },
5755                 _ => panic!("Unexpected event"),
5756         }
5757 }
5758
5759 // Test that if multiple HTLCs are released from the holding cell and one is
5760 // valid but the other is no longer valid upon release, the valid HTLC can be
5761 // successfully completed while the other one fails as expected.
5762 #[test]
5763 fn test_free_and_fail_holding_cell_htlcs() {
5764         let chanmon_cfgs = create_chanmon_cfgs(2);
5765         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5766         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5767         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5768         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5769
5770         // First nodes[0] generates an update_fee, setting the channel's
5771         // pending_update_fee.
5772         {
5773                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5774                 *feerate_lock += 200;
5775         }
5776         nodes[0].node.timer_tick_occurred();
5777         check_added_monitors!(nodes[0], 1);
5778
5779         let events = nodes[0].node.get_and_clear_pending_msg_events();
5780         assert_eq!(events.len(), 1);
5781         let (update_msg, commitment_signed) = match events[0] {
5782                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5783                         (update_fee.as_ref(), commitment_signed)
5784                 },
5785                 _ => panic!("Unexpected event"),
5786         };
5787
5788         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5789
5790         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5791         let channel_reserve = chan_stat.channel_reserve_msat;
5792         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5793         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5794
5795         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5796         let amt_1 = 20000;
5797         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5798         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5799         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5800
5801         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5802         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5803                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5804         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5805         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5806         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5807         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5808                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5809         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5810         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5811
5812         // Flush the pending fee update.
5813         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5814         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5815         check_added_monitors!(nodes[1], 1);
5816         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5817         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5818         check_added_monitors!(nodes[0], 2);
5819
5820         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5821         // but now that the fee has been raised the second payment will now fail, causing us
5822         // to surface its failure to the user. The first payment should succeed.
5823         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5824         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5825         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);
5826
5827         // Check that the second payment failed to be sent out.
5828         let events = nodes[0].node.get_and_clear_pending_events();
5829         assert_eq!(events.len(), 2);
5830         match &events[0] {
5831                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5832                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5833                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5834                         assert_eq!(*payment_failed_permanently, false);
5835                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5836                 },
5837                 _ => panic!("Unexpected event"),
5838         }
5839         match &events[1] {
5840                 &Event::PaymentFailed { ref payment_hash, .. } => {
5841                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5842                 },
5843                 _ => panic!("Unexpected event"),
5844         }
5845
5846         // Complete the first payment and the RAA from the fee update.
5847         let (payment_event, send_raa_event) = {
5848                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5849                 assert_eq!(msgs.len(), 2);
5850                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5851         };
5852         let raa = match send_raa_event {
5853                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5854                 _ => panic!("Unexpected event"),
5855         };
5856         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5857         check_added_monitors!(nodes[1], 1);
5858         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5859         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5860         let events = nodes[1].node.get_and_clear_pending_events();
5861         assert_eq!(events.len(), 1);
5862         match events[0] {
5863                 Event::PendingHTLCsForwardable { .. } => {},
5864                 _ => panic!("Unexpected event"),
5865         }
5866         nodes[1].node.process_pending_htlc_forwards();
5867         let events = nodes[1].node.get_and_clear_pending_events();
5868         assert_eq!(events.len(), 1);
5869         match events[0] {
5870                 Event::PaymentClaimable { .. } => {},
5871                 _ => panic!("Unexpected event"),
5872         }
5873         nodes[1].node.claim_funds(payment_preimage_1);
5874         check_added_monitors!(nodes[1], 1);
5875         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5876
5877         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5878         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5879         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5880         expect_payment_sent!(nodes[0], payment_preimage_1);
5881 }
5882
5883 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5884 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5885 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5886 // once it's freed.
5887 #[test]
5888 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5889         let chanmon_cfgs = create_chanmon_cfgs(3);
5890         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5891         // Avoid having to include routing fees in calculations
5892         let mut config = test_default_channel_config();
5893         config.channel_config.forwarding_fee_base_msat = 0;
5894         config.channel_config.forwarding_fee_proportional_millionths = 0;
5895         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5896         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5897         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5898         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5899
5900         // First nodes[1] generates an update_fee, setting the channel's
5901         // pending_update_fee.
5902         {
5903                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5904                 *feerate_lock += 20;
5905         }
5906         nodes[1].node.timer_tick_occurred();
5907         check_added_monitors!(nodes[1], 1);
5908
5909         let events = nodes[1].node.get_and_clear_pending_msg_events();
5910         assert_eq!(events.len(), 1);
5911         let (update_msg, commitment_signed) = match events[0] {
5912                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5913                         (update_fee.as_ref(), commitment_signed)
5914                 },
5915                 _ => panic!("Unexpected event"),
5916         };
5917
5918         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5919
5920         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5921         let channel_reserve = chan_stat.channel_reserve_msat;
5922         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5923         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
5924
5925         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5926         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5927         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5928         let payment_event = {
5929                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5930                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5931                 check_added_monitors!(nodes[0], 1);
5932
5933                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5934                 assert_eq!(events.len(), 1);
5935
5936                 SendEvent::from_event(events.remove(0))
5937         };
5938         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5939         check_added_monitors!(nodes[1], 0);
5940         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5941         expect_pending_htlcs_forwardable!(nodes[1]);
5942
5943         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5944         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5945
5946         // Flush the pending fee update.
5947         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5948         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5949         check_added_monitors!(nodes[2], 1);
5950         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5951         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5952         check_added_monitors!(nodes[1], 2);
5953
5954         // A final RAA message is generated to finalize the fee update.
5955         let events = nodes[1].node.get_and_clear_pending_msg_events();
5956         assert_eq!(events.len(), 1);
5957
5958         let raa_msg = match &events[0] {
5959                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5960                         msg.clone()
5961                 },
5962                 _ => panic!("Unexpected event"),
5963         };
5964
5965         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5966         check_added_monitors!(nodes[2], 1);
5967         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5968
5969         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5970         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5971         assert_eq!(process_htlc_forwards_event.len(), 2);
5972         match &process_htlc_forwards_event[0] {
5973                 &Event::PendingHTLCsForwardable { .. } => {},
5974                 _ => panic!("Unexpected event"),
5975         }
5976
5977         // In response, we call ChannelManager's process_pending_htlc_forwards
5978         nodes[1].node.process_pending_htlc_forwards();
5979         check_added_monitors!(nodes[1], 1);
5980
5981         // This causes the HTLC to be failed backwards.
5982         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5983         assert_eq!(fail_event.len(), 1);
5984         let (fail_msg, commitment_signed) = match &fail_event[0] {
5985                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5986                         assert_eq!(updates.update_add_htlcs.len(), 0);
5987                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5988                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5989                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5990                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5991                 },
5992                 _ => panic!("Unexpected event"),
5993         };
5994
5995         // Pass the failure messages back to nodes[0].
5996         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5997         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5998
5999         // Complete the HTLC failure+removal process.
6000         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6001         check_added_monitors!(nodes[0], 1);
6002         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6003         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6004         check_added_monitors!(nodes[1], 2);
6005         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6006         assert_eq!(final_raa_event.len(), 1);
6007         let raa = match &final_raa_event[0] {
6008                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6009                 _ => panic!("Unexpected event"),
6010         };
6011         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6012         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6013         check_added_monitors!(nodes[0], 1);
6014 }
6015
6016 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6017 // 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.
6018 //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.
6019
6020 #[test]
6021 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6022         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6023         let chanmon_cfgs = create_chanmon_cfgs(2);
6024         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6025         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6026         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6027         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6028
6029         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6030         route.paths[0].hops[0].fee_msat = 100;
6031
6032         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6033                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6034                 ), true, APIError::ChannelUnavailable { .. }, {});
6035         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6036 }
6037
6038 #[test]
6039 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6040         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6041         let chanmon_cfgs = create_chanmon_cfgs(2);
6042         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6043         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6044         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6045         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6046
6047         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6048         route.paths[0].hops[0].fee_msat = 0;
6049         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6050                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6051                 true, APIError::ChannelUnavailable { ref err },
6052                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6053
6054         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6055         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6056 }
6057
6058 #[test]
6059 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6060         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6061         let chanmon_cfgs = create_chanmon_cfgs(2);
6062         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6063         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6064         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6065         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6066
6067         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6068         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6069                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6070         check_added_monitors!(nodes[0], 1);
6071         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6072         updates.update_add_htlcs[0].amount_msat = 0;
6073
6074         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6075         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6076         check_closed_broadcast!(nodes[1], true).unwrap();
6077         check_added_monitors!(nodes[1], 1);
6078         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6079 }
6080
6081 #[test]
6082 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6083         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6084         //It is enforced when constructing a route.
6085         let chanmon_cfgs = create_chanmon_cfgs(2);
6086         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6087         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6088         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6089         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6090
6091         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6092                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6093         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6094         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6095         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6096                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6097                 ), true, APIError::InvalidRoute { ref err },
6098                 assert_eq!(err, &"Channel CLTV overflowed?"));
6099 }
6100
6101 #[test]
6102 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6103         //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.
6104         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6105         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6106         let chanmon_cfgs = create_chanmon_cfgs(2);
6107         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6108         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6109         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6110         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6111         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6112                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6113
6114         // Fetch a route in advance as we will be unable to once we're unable to send.
6115         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6116         for i in 0..max_accepted_htlcs {
6117                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6118                 let payment_event = {
6119                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6120                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6121                         check_added_monitors!(nodes[0], 1);
6122
6123                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6124                         assert_eq!(events.len(), 1);
6125                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6126                                 assert_eq!(htlcs[0].htlc_id, i);
6127                         } else {
6128                                 assert!(false);
6129                         }
6130                         SendEvent::from_event(events.remove(0))
6131                 };
6132                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6133                 check_added_monitors!(nodes[1], 0);
6134                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6135
6136                 expect_pending_htlcs_forwardable!(nodes[1]);
6137                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6138         }
6139         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6140                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6141                 ), true, APIError::ChannelUnavailable { .. }, {});
6142
6143         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6144 }
6145
6146 #[test]
6147 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6148         //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.
6149         let chanmon_cfgs = create_chanmon_cfgs(2);
6150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6152         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6153         let channel_value = 100000;
6154         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6155         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6156
6157         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6158
6159         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6160         // Manually create a route over our max in flight (which our router normally automatically
6161         // limits us to.
6162         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6163         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6164                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6165                 ), true, APIError::ChannelUnavailable { .. }, {});
6166         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6167
6168         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6169 }
6170
6171 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6172 #[test]
6173 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6174         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6175         let chanmon_cfgs = create_chanmon_cfgs(2);
6176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6178         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6179         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6180         let htlc_minimum_msat: u64;
6181         {
6182                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6183                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6184                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6185                 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6186         }
6187
6188         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6189         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6190                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6191         check_added_monitors!(nodes[0], 1);
6192         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6193         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6194         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6195         assert!(nodes[1].node.list_channels().is_empty());
6196         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6197         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()));
6198         check_added_monitors!(nodes[1], 1);
6199         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6200 }
6201
6202 #[test]
6203 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6204         //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
6205         let chanmon_cfgs = create_chanmon_cfgs(2);
6206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6208         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6209         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6210
6211         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6212         let channel_reserve = chan_stat.channel_reserve_msat;
6213         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6214         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6215         // The 2* and +1 are for the fee spike reserve.
6216         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6217
6218         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6219         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6220         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6221                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6222         check_added_monitors!(nodes[0], 1);
6223         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6224
6225         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6226         // at this time channel-initiatee receivers are not required to enforce that senders
6227         // respect the fee_spike_reserve.
6228         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6229         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6230
6231         assert!(nodes[1].node.list_channels().is_empty());
6232         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6233         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6234         check_added_monitors!(nodes[1], 1);
6235         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6236 }
6237
6238 #[test]
6239 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6240         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6241         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6242         let chanmon_cfgs = create_chanmon_cfgs(2);
6243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6246         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6247
6248         let send_amt = 3999999;
6249         let (mut route, our_payment_hash, _, our_payment_secret) =
6250                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6251         route.paths[0].hops[0].fee_msat = send_amt;
6252         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6253         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6254         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6255         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6256                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6257         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6258
6259         let mut msg = msgs::UpdateAddHTLC {
6260                 channel_id: chan.2,
6261                 htlc_id: 0,
6262                 amount_msat: 1000,
6263                 payment_hash: our_payment_hash,
6264                 cltv_expiry: htlc_cltv,
6265                 onion_routing_packet: onion_packet.clone(),
6266                 skimmed_fee_msat: None,
6267         };
6268
6269         for i in 0..50 {
6270                 msg.htlc_id = i as u64;
6271                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6272         }
6273         msg.htlc_id = (50) as u64;
6274         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6275
6276         assert!(nodes[1].node.list_channels().is_empty());
6277         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6278         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6279         check_added_monitors!(nodes[1], 1);
6280         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6281 }
6282
6283 #[test]
6284 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6285         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6286         let chanmon_cfgs = create_chanmon_cfgs(2);
6287         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6288         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6289         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6290         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6291
6292         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6293         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6294                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6295         check_added_monitors!(nodes[0], 1);
6296         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6297         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;
6298         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6299
6300         assert!(nodes[1].node.list_channels().is_empty());
6301         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6302         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6303         check_added_monitors!(nodes[1], 1);
6304         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6305 }
6306
6307 #[test]
6308 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6309         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6310         let chanmon_cfgs = create_chanmon_cfgs(2);
6311         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6312         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6313         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6314
6315         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6316         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6317         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6318                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6319         check_added_monitors!(nodes[0], 1);
6320         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6321         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6322         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6323
6324         assert!(nodes[1].node.list_channels().is_empty());
6325         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6326         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6327         check_added_monitors!(nodes[1], 1);
6328         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6329 }
6330
6331 #[test]
6332 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6333         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6334         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6335         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6336         let chanmon_cfgs = create_chanmon_cfgs(2);
6337         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6338         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6339         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6340
6341         create_announced_chan_between_nodes(&nodes, 0, 1);
6342         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6343         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6344                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6345         check_added_monitors!(nodes[0], 1);
6346         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6347         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6348
6349         //Disconnect and Reconnect
6350         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6351         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6352         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6353                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6354         }, true).unwrap();
6355         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6356         assert_eq!(reestablish_1.len(), 1);
6357         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6358                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6359         }, false).unwrap();
6360         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6361         assert_eq!(reestablish_2.len(), 1);
6362         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6363         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6364         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6365         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6366
6367         //Resend HTLC
6368         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6369         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6370         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6371         check_added_monitors!(nodes[1], 1);
6372         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6373
6374         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6375
6376         assert!(nodes[1].node.list_channels().is_empty());
6377         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6378         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6379         check_added_monitors!(nodes[1], 1);
6380         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6381 }
6382
6383 #[test]
6384 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6385         //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.
6386
6387         let chanmon_cfgs = create_chanmon_cfgs(2);
6388         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6389         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6390         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6391         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6392         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6393         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6394                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6395
6396         check_added_monitors!(nodes[0], 1);
6397         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6398         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6399
6400         let update_msg = msgs::UpdateFulfillHTLC{
6401                 channel_id: chan.2,
6402                 htlc_id: 0,
6403                 payment_preimage: our_payment_preimage,
6404         };
6405
6406         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6407
6408         assert!(nodes[0].node.list_channels().is_empty());
6409         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6410         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()));
6411         check_added_monitors!(nodes[0], 1);
6412         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6413 }
6414
6415 #[test]
6416 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6417         //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.
6418
6419         let chanmon_cfgs = create_chanmon_cfgs(2);
6420         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6421         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6422         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6423         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6424
6425         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6426         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6427                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6428         check_added_monitors!(nodes[0], 1);
6429         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6430         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6431
6432         let update_msg = msgs::UpdateFailHTLC{
6433                 channel_id: chan.2,
6434                 htlc_id: 0,
6435                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6436         };
6437
6438         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6439
6440         assert!(nodes[0].node.list_channels().is_empty());
6441         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6442         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()));
6443         check_added_monitors!(nodes[0], 1);
6444         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6445 }
6446
6447 #[test]
6448 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6449         //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.
6450
6451         let chanmon_cfgs = create_chanmon_cfgs(2);
6452         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6453         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6454         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6455         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6456
6457         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6458         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6459                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6460         check_added_monitors!(nodes[0], 1);
6461         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6462         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6463         let update_msg = msgs::UpdateFailMalformedHTLC{
6464                 channel_id: chan.2,
6465                 htlc_id: 0,
6466                 sha256_of_onion: [1; 32],
6467                 failure_code: 0x8000,
6468         };
6469
6470         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6471
6472         assert!(nodes[0].node.list_channels().is_empty());
6473         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6474         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()));
6475         check_added_monitors!(nodes[0], 1);
6476         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6477 }
6478
6479 #[test]
6480 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6481         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6482
6483         let chanmon_cfgs = create_chanmon_cfgs(2);
6484         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6485         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6486         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6487         create_announced_chan_between_nodes(&nodes, 0, 1);
6488
6489         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6490
6491         nodes[1].node.claim_funds(our_payment_preimage);
6492         check_added_monitors!(nodes[1], 1);
6493         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6494
6495         let events = nodes[1].node.get_and_clear_pending_msg_events();
6496         assert_eq!(events.len(), 1);
6497         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6498                 match events[0] {
6499                         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, .. } } => {
6500                                 assert!(update_add_htlcs.is_empty());
6501                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6502                                 assert!(update_fail_htlcs.is_empty());
6503                                 assert!(update_fail_malformed_htlcs.is_empty());
6504                                 assert!(update_fee.is_none());
6505                                 update_fulfill_htlcs[0].clone()
6506                         },
6507                         _ => panic!("Unexpected event"),
6508                 }
6509         };
6510
6511         update_fulfill_msg.htlc_id = 1;
6512
6513         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6514
6515         assert!(nodes[0].node.list_channels().is_empty());
6516         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6517         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6518         check_added_monitors!(nodes[0], 1);
6519         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6520 }
6521
6522 #[test]
6523 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6524         //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.
6525
6526         let chanmon_cfgs = create_chanmon_cfgs(2);
6527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530         create_announced_chan_between_nodes(&nodes, 0, 1);
6531
6532         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6533
6534         nodes[1].node.claim_funds(our_payment_preimage);
6535         check_added_monitors!(nodes[1], 1);
6536         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6537
6538         let events = nodes[1].node.get_and_clear_pending_msg_events();
6539         assert_eq!(events.len(), 1);
6540         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6541                 match events[0] {
6542                         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, .. } } => {
6543                                 assert!(update_add_htlcs.is_empty());
6544                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6545                                 assert!(update_fail_htlcs.is_empty());
6546                                 assert!(update_fail_malformed_htlcs.is_empty());
6547                                 assert!(update_fee.is_none());
6548                                 update_fulfill_htlcs[0].clone()
6549                         },
6550                         _ => panic!("Unexpected event"),
6551                 }
6552         };
6553
6554         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6555
6556         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6557
6558         assert!(nodes[0].node.list_channels().is_empty());
6559         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6560         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6561         check_added_monitors!(nodes[0], 1);
6562         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6563 }
6564
6565 #[test]
6566 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6567         //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.
6568
6569         let chanmon_cfgs = create_chanmon_cfgs(2);
6570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6574
6575         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6576         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6577                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6578         check_added_monitors!(nodes[0], 1);
6579
6580         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6581         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6582
6583         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584         check_added_monitors!(nodes[1], 0);
6585         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6586
6587         let events = nodes[1].node.get_and_clear_pending_msg_events();
6588
6589         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6590                 match events[0] {
6591                         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, .. } } => {
6592                                 assert!(update_add_htlcs.is_empty());
6593                                 assert!(update_fulfill_htlcs.is_empty());
6594                                 assert!(update_fail_htlcs.is_empty());
6595                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6596                                 assert!(update_fee.is_none());
6597                                 update_fail_malformed_htlcs[0].clone()
6598                         },
6599                         _ => panic!("Unexpected event"),
6600                 }
6601         };
6602         update_msg.failure_code &= !0x8000;
6603         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6604
6605         assert!(nodes[0].node.list_channels().is_empty());
6606         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6607         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6608         check_added_monitors!(nodes[0], 1);
6609         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6610 }
6611
6612 #[test]
6613 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6614         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6615         //    * 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.
6616
6617         let chanmon_cfgs = create_chanmon_cfgs(3);
6618         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6619         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6620         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6621         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6622         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6623
6624         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6625
6626         //First hop
6627         let mut payment_event = {
6628                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6629                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6630                 check_added_monitors!(nodes[0], 1);
6631                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6632                 assert_eq!(events.len(), 1);
6633                 SendEvent::from_event(events.remove(0))
6634         };
6635         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6636         check_added_monitors!(nodes[1], 0);
6637         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6638         expect_pending_htlcs_forwardable!(nodes[1]);
6639         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6640         assert_eq!(events_2.len(), 1);
6641         check_added_monitors!(nodes[1], 1);
6642         payment_event = SendEvent::from_event(events_2.remove(0));
6643         assert_eq!(payment_event.msgs.len(), 1);
6644
6645         //Second Hop
6646         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6647         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6648         check_added_monitors!(nodes[2], 0);
6649         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6650
6651         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6652         assert_eq!(events_3.len(), 1);
6653         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6654                 match events_3[0] {
6655                         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 } } => {
6656                                 assert!(update_add_htlcs.is_empty());
6657                                 assert!(update_fulfill_htlcs.is_empty());
6658                                 assert!(update_fail_htlcs.is_empty());
6659                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6660                                 assert!(update_fee.is_none());
6661                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6662                         },
6663                         _ => panic!("Unexpected event"),
6664                 }
6665         };
6666
6667         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6668
6669         check_added_monitors!(nodes[1], 0);
6670         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6671         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 }]);
6672         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6673         assert_eq!(events_4.len(), 1);
6674
6675         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6676         match events_4[0] {
6677                 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, .. } } => {
6678                         assert!(update_add_htlcs.is_empty());
6679                         assert!(update_fulfill_htlcs.is_empty());
6680                         assert_eq!(update_fail_htlcs.len(), 1);
6681                         assert!(update_fail_malformed_htlcs.is_empty());
6682                         assert!(update_fee.is_none());
6683                 },
6684                 _ => panic!("Unexpected event"),
6685         };
6686
6687         check_added_monitors!(nodes[1], 1);
6688 }
6689
6690 #[test]
6691 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6692         let chanmon_cfgs = create_chanmon_cfgs(3);
6693         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6694         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6695         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6696         create_announced_chan_between_nodes(&nodes, 0, 1);
6697         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6698
6699         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6700
6701         // First hop
6702         let mut payment_event = {
6703                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6704                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6705                 check_added_monitors!(nodes[0], 1);
6706                 SendEvent::from_node(&nodes[0])
6707         };
6708
6709         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6710         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6711         expect_pending_htlcs_forwardable!(nodes[1]);
6712         check_added_monitors!(nodes[1], 1);
6713         payment_event = SendEvent::from_node(&nodes[1]);
6714         assert_eq!(payment_event.msgs.len(), 1);
6715
6716         // Second Hop
6717         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6718         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6719         check_added_monitors!(nodes[2], 0);
6720         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6721
6722         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6723         assert_eq!(events_3.len(), 1);
6724         match events_3[0] {
6725                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6726                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6727                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6728                         update_msg.failure_code |= 0x2000;
6729
6730                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6731                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6732                 },
6733                 _ => panic!("Unexpected event"),
6734         }
6735
6736         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6737                 vec![HTLCDestination::NextHopChannel {
6738                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6739         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6740         assert_eq!(events_4.len(), 1);
6741         check_added_monitors!(nodes[1], 1);
6742
6743         match events_4[0] {
6744                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6745                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6746                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6747                 },
6748                 _ => panic!("Unexpected event"),
6749         }
6750
6751         let events_5 = nodes[0].node.get_and_clear_pending_events();
6752         assert_eq!(events_5.len(), 2);
6753
6754         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6755         // the node originating the error to its next hop.
6756         match events_5[0] {
6757                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6758                 } => {
6759                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6760                         assert!(is_permanent);
6761                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6762                 },
6763                 _ => panic!("Unexpected event"),
6764         }
6765         match events_5[1] {
6766                 Event::PaymentFailed { payment_hash, .. } => {
6767                         assert_eq!(payment_hash, our_payment_hash);
6768                 },
6769                 _ => panic!("Unexpected event"),
6770         }
6771
6772         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6773 }
6774
6775 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6776         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6777         // 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
6778         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6779
6780         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6781         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6782         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6783         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6784         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6785         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6786
6787         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6788                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6789
6790         // We route 2 dust-HTLCs between A and B
6791         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6792         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6793         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6794
6795         // Cache one local commitment tx as previous
6796         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6797
6798         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6799         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6800         check_added_monitors!(nodes[1], 0);
6801         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6802         check_added_monitors!(nodes[1], 1);
6803
6804         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6805         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6806         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6807         check_added_monitors!(nodes[0], 1);
6808
6809         // Cache one local commitment tx as lastest
6810         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6811
6812         let events = nodes[0].node.get_and_clear_pending_msg_events();
6813         match events[0] {
6814                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6815                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6816                 },
6817                 _ => panic!("Unexpected event"),
6818         }
6819         match events[1] {
6820                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6821                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6822                 },
6823                 _ => panic!("Unexpected event"),
6824         }
6825
6826         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6827         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6828         if announce_latest {
6829                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6830         } else {
6831                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6832         }
6833
6834         check_closed_broadcast!(nodes[0], true);
6835         check_added_monitors!(nodes[0], 1);
6836         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6837
6838         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6839         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6840         let events = nodes[0].node.get_and_clear_pending_events();
6841         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6842         assert_eq!(events.len(), 4);
6843         let mut first_failed = false;
6844         for event in events {
6845                 match event {
6846                         Event::PaymentPathFailed { payment_hash, .. } => {
6847                                 if payment_hash == payment_hash_1 {
6848                                         assert!(!first_failed);
6849                                         first_failed = true;
6850                                 } else {
6851                                         assert_eq!(payment_hash, payment_hash_2);
6852                                 }
6853                         },
6854                         Event::PaymentFailed { .. } => {}
6855                         _ => panic!("Unexpected event"),
6856                 }
6857         }
6858 }
6859
6860 #[test]
6861 fn test_failure_delay_dust_htlc_local_commitment() {
6862         do_test_failure_delay_dust_htlc_local_commitment(true);
6863         do_test_failure_delay_dust_htlc_local_commitment(false);
6864 }
6865
6866 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6867         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6868         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6869         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6870         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6871         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6872         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6873
6874         let chanmon_cfgs = create_chanmon_cfgs(3);
6875         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6876         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6877         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6878         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6879
6880         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6881                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6882
6883         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6884         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6885
6886         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6887         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6888
6889         // We revoked bs_commitment_tx
6890         if revoked {
6891                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6892                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6893         }
6894
6895         let mut timeout_tx = Vec::new();
6896         if local {
6897                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6898                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6899                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6900                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6901                 expect_payment_failed!(nodes[0], dust_hash, false);
6902
6903                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6904                 check_closed_broadcast!(nodes[0], true);
6905                 check_added_monitors!(nodes[0], 1);
6906                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6907                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6908                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6909                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6910                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6911                 mine_transaction(&nodes[0], &timeout_tx[0]);
6912                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6913                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6914         } else {
6915                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6916                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6917                 check_closed_broadcast!(nodes[0], true);
6918                 check_added_monitors!(nodes[0], 1);
6919                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6920                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6921
6922                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6923                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6924                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6925                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6926                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6927                 // dust HTLC should have been failed.
6928                 expect_payment_failed!(nodes[0], dust_hash, false);
6929
6930                 if !revoked {
6931                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6932                 } else {
6933                         assert_eq!(timeout_tx[0].lock_time.0, 11);
6934                 }
6935                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6936                 mine_transaction(&nodes[0], &timeout_tx[0]);
6937                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6938                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6939                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6940         }
6941 }
6942
6943 #[test]
6944 fn test_sweep_outbound_htlc_failure_update() {
6945         do_test_sweep_outbound_htlc_failure_update(false, true);
6946         do_test_sweep_outbound_htlc_failure_update(false, false);
6947         do_test_sweep_outbound_htlc_failure_update(true, false);
6948 }
6949
6950 #[test]
6951 fn test_user_configurable_csv_delay() {
6952         // We test our channel constructors yield errors when we pass them absurd csv delay
6953
6954         let mut low_our_to_self_config = UserConfig::default();
6955         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6956         let mut high_their_to_self_config = UserConfig::default();
6957         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6958         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6959         let chanmon_cfgs = create_chanmon_cfgs(2);
6960         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6961         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6962         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6963
6964         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
6965         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6966                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6967                 &low_our_to_self_config, 0, 42)
6968         {
6969                 match error {
6970                         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())); },
6971                         _ => panic!("Unexpected event"),
6972                 }
6973         } else { assert!(false) }
6974
6975         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
6976         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6977         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6978         open_channel.to_self_delay = 200;
6979         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6980                 &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,
6981                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6982         {
6983                 match error {
6984                         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()));  },
6985                         _ => panic!("Unexpected event"),
6986                 }
6987         } else { assert!(false); }
6988
6989         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6990         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6991         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()));
6992         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6993         accept_channel.to_self_delay = 200;
6994         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6995         let reason_msg;
6996         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6997                 match action {
6998                         &ErrorAction::SendErrorMessage { ref msg } => {
6999                                 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()));
7000                                 reason_msg = msg.data.clone();
7001                         },
7002                         _ => { panic!(); }
7003                 }
7004         } else { panic!(); }
7005         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7006
7007         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7008         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7009         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7010         open_channel.to_self_delay = 200;
7011         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7012                 &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,
7013                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7014         {
7015                 match error {
7016                         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())); },
7017                         _ => panic!("Unexpected event"),
7018                 }
7019         } else { assert!(false); }
7020 }
7021
7022 #[test]
7023 fn test_check_htlc_underpaying() {
7024         // Send payment through A -> B but A is maliciously
7025         // sending a probe payment (i.e less than expected value0
7026         // to B, B should refuse payment.
7027
7028         let chanmon_cfgs = create_chanmon_cfgs(2);
7029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7031         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7032
7033         // Create some initial channels
7034         create_announced_chan_between_nodes(&nodes, 0, 1);
7035
7036         let scorer = test_utils::TestScorer::new();
7037         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7038         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();
7039         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();
7040         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7041         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7042         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7043                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7044         check_added_monitors!(nodes[0], 1);
7045
7046         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7047         assert_eq!(events.len(), 1);
7048         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7049         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7050         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7051
7052         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7053         // and then will wait a second random delay before failing the HTLC back:
7054         expect_pending_htlcs_forwardable!(nodes[1]);
7055         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7056
7057         // Node 3 is expecting payment of 100_000 but received 10_000,
7058         // it should fail htlc like we didn't know the preimage.
7059         nodes[1].node.process_pending_htlc_forwards();
7060
7061         let events = nodes[1].node.get_and_clear_pending_msg_events();
7062         assert_eq!(events.len(), 1);
7063         let (update_fail_htlc, commitment_signed) = match events[0] {
7064                 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 } } => {
7065                         assert!(update_add_htlcs.is_empty());
7066                         assert!(update_fulfill_htlcs.is_empty());
7067                         assert_eq!(update_fail_htlcs.len(), 1);
7068                         assert!(update_fail_malformed_htlcs.is_empty());
7069                         assert!(update_fee.is_none());
7070                         (update_fail_htlcs[0].clone(), commitment_signed)
7071                 },
7072                 _ => panic!("Unexpected event"),
7073         };
7074         check_added_monitors!(nodes[1], 1);
7075
7076         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7077         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7078
7079         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7080         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7081         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7082         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7083 }
7084
7085 #[test]
7086 fn test_announce_disable_channels() {
7087         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7088         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7089
7090         let chanmon_cfgs = create_chanmon_cfgs(2);
7091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7093         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7094
7095         create_announced_chan_between_nodes(&nodes, 0, 1);
7096         create_announced_chan_between_nodes(&nodes, 1, 0);
7097         create_announced_chan_between_nodes(&nodes, 0, 1);
7098
7099         // Disconnect peers
7100         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7101         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7102
7103         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7104                 nodes[0].node.timer_tick_occurred();
7105         }
7106         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7107         assert_eq!(msg_events.len(), 3);
7108         let mut chans_disabled = HashMap::new();
7109         for e in msg_events {
7110                 match e {
7111                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7112                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7113                                 // Check that each channel gets updated exactly once
7114                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7115                                         panic!("Generated ChannelUpdate for wrong chan!");
7116                                 }
7117                         },
7118                         _ => panic!("Unexpected event"),
7119                 }
7120         }
7121         // Reconnect peers
7122         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7123                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7124         }, true).unwrap();
7125         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7126         assert_eq!(reestablish_1.len(), 3);
7127         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7128                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7129         }, false).unwrap();
7130         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7131         assert_eq!(reestablish_2.len(), 3);
7132
7133         // Reestablish chan_1
7134         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
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[0]);
7137         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7138         // Reestablish chan_2
7139         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
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[1]);
7142         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7143         // Reestablish chan_3
7144         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7145         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7146         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7147         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7148
7149         for _ in 0..ENABLE_GOSSIP_TICKS {
7150                 nodes[0].node.timer_tick_occurred();
7151         }
7152         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7153         nodes[0].node.timer_tick_occurred();
7154         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7155         assert_eq!(msg_events.len(), 3);
7156         for e in msg_events {
7157                 match e {
7158                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7159                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7160                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7161                                         // Each update should have a higher timestamp than the previous one, replacing
7162                                         // the old one.
7163                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7164                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7165                                 }
7166                         },
7167                         _ => panic!("Unexpected event"),
7168                 }
7169         }
7170         // Check that each channel gets updated exactly once
7171         assert!(chans_disabled.is_empty());
7172 }
7173
7174 #[test]
7175 fn test_bump_penalty_txn_on_revoked_commitment() {
7176         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7177         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7178
7179         let chanmon_cfgs = create_chanmon_cfgs(2);
7180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7182         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7183
7184         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7185
7186         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7187         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7188                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7189         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7190         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7191
7192         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7193         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7194         assert_eq!(revoked_txn[0].output.len(), 4);
7195         assert_eq!(revoked_txn[0].input.len(), 1);
7196         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7197         let revoked_txid = revoked_txn[0].txid();
7198
7199         let mut penalty_sum = 0;
7200         for outp in revoked_txn[0].output.iter() {
7201                 if outp.script_pubkey.is_v0_p2wsh() {
7202                         penalty_sum += outp.value;
7203                 }
7204         }
7205
7206         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7207         let header_114 = connect_blocks(&nodes[1], 14);
7208
7209         // Actually revoke tx by claiming a HTLC
7210         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7211         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7212         check_added_monitors!(nodes[1], 1);
7213
7214         // One or more justice tx should have been broadcast, check it
7215         let penalty_1;
7216         let feerate_1;
7217         {
7218                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7219                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7220                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7221                 assert_eq!(node_txn[0].output.len(), 1);
7222                 check_spends!(node_txn[0], revoked_txn[0]);
7223                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7224                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7225                 penalty_1 = node_txn[0].txid();
7226                 node_txn.clear();
7227         };
7228
7229         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7230         connect_blocks(&nodes[1], 15);
7231         let mut penalty_2 = penalty_1;
7232         let mut feerate_2 = 0;
7233         {
7234                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7235                 assert_eq!(node_txn.len(), 1);
7236                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7237                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7238                         assert_eq!(node_txn[0].output.len(), 1);
7239                         check_spends!(node_txn[0], revoked_txn[0]);
7240                         penalty_2 = node_txn[0].txid();
7241                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7242                         assert_ne!(penalty_2, penalty_1);
7243                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7244                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7245                         // Verify 25% bump heuristic
7246                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7247                         node_txn.clear();
7248                 }
7249         }
7250         assert_ne!(feerate_2, 0);
7251
7252         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7253         connect_blocks(&nodes[1], 1);
7254         let penalty_3;
7255         let mut feerate_3 = 0;
7256         {
7257                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7258                 assert_eq!(node_txn.len(), 1);
7259                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7260                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7261                         assert_eq!(node_txn[0].output.len(), 1);
7262                         check_spends!(node_txn[0], revoked_txn[0]);
7263                         penalty_3 = node_txn[0].txid();
7264                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7265                         assert_ne!(penalty_3, penalty_2);
7266                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7267                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7268                         // Verify 25% bump heuristic
7269                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7270                         node_txn.clear();
7271                 }
7272         }
7273         assert_ne!(feerate_3, 0);
7274
7275         nodes[1].node.get_and_clear_pending_events();
7276         nodes[1].node.get_and_clear_pending_msg_events();
7277 }
7278
7279 #[test]
7280 fn test_bump_penalty_txn_on_revoked_htlcs() {
7281         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7282         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7283
7284         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7285         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7286         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7287         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7288         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7289
7290         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7291         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7292         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7293         let scorer = test_utils::TestScorer::new();
7294         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7295         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7296                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7297         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7298         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7299         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7300                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7301         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7302
7303         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7304         assert_eq!(revoked_local_txn[0].input.len(), 1);
7305         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7306
7307         // Revoke local commitment tx
7308         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7309
7310         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7311         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7312         check_closed_broadcast!(nodes[1], true);
7313         check_added_monitors!(nodes[1], 1);
7314         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7315         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7316
7317         let revoked_htlc_txn = {
7318                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7319                 assert_eq!(txn.len(), 2);
7320
7321                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7322                 assert_eq!(txn[0].input.len(), 1);
7323                 check_spends!(txn[0], revoked_local_txn[0]);
7324
7325                 assert_eq!(txn[1].input.len(), 1);
7326                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7327                 assert_eq!(txn[1].output.len(), 1);
7328                 check_spends!(txn[1], revoked_local_txn[0]);
7329
7330                 txn
7331         };
7332
7333         // Broadcast set of revoked txn on A
7334         let hash_128 = connect_blocks(&nodes[0], 40);
7335         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7336         connect_block(&nodes[0], &block_11);
7337         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7338         connect_block(&nodes[0], &block_129);
7339         let events = nodes[0].node.get_and_clear_pending_events();
7340         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7341         match events.last().unwrap() {
7342                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7343                 _ => panic!("Unexpected event"),
7344         }
7345         let first;
7346         let feerate_1;
7347         let penalty_txn;
7348         {
7349                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7350                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7351                 // Verify claim tx are spending revoked HTLC txn
7352
7353                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7354                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7355                 // which are included in the same block (they are broadcasted because we scan the
7356                 // transactions linearly and generate claims as we go, they likely should be removed in the
7357                 // future).
7358                 assert_eq!(node_txn[0].input.len(), 1);
7359                 check_spends!(node_txn[0], revoked_local_txn[0]);
7360                 assert_eq!(node_txn[1].input.len(), 1);
7361                 check_spends!(node_txn[1], revoked_local_txn[0]);
7362                 assert_eq!(node_txn[2].input.len(), 1);
7363                 check_spends!(node_txn[2], revoked_local_txn[0]);
7364
7365                 // Each of the three justice transactions claim a separate (single) output of the three
7366                 // available, which we check here:
7367                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7368                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7369                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7370
7371                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7372                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7373
7374                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7375                 // output, checked above).
7376                 assert_eq!(node_txn[3].input.len(), 2);
7377                 assert_eq!(node_txn[3].output.len(), 1);
7378                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7379
7380                 first = node_txn[3].txid();
7381                 // Store both feerates for later comparison
7382                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7383                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7384                 penalty_txn = vec![node_txn[2].clone()];
7385                 node_txn.clear();
7386         }
7387
7388         // Connect one more block to see if bumped penalty are issued for HTLC txn
7389         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7390         connect_block(&nodes[0], &block_130);
7391         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7392         connect_block(&nodes[0], &block_131);
7393
7394         // Few more blocks to confirm penalty txn
7395         connect_blocks(&nodes[0], 4);
7396         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7397         let header_144 = connect_blocks(&nodes[0], 9);
7398         let node_txn = {
7399                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7400                 assert_eq!(node_txn.len(), 1);
7401
7402                 assert_eq!(node_txn[0].input.len(), 2);
7403                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7404                 // Verify bumped tx is different and 25% bump heuristic
7405                 assert_ne!(first, node_txn[0].txid());
7406                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7407                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7408                 assert!(feerate_2 * 100 > feerate_1 * 125);
7409                 let txn = vec![node_txn[0].clone()];
7410                 node_txn.clear();
7411                 txn
7412         };
7413         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7414         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7415         connect_blocks(&nodes[0], 20);
7416         {
7417                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7418                 // We verify than no new transaction has been broadcast because previously
7419                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7420                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7421                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7422                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7423                 // up bumped justice generation.
7424                 assert_eq!(node_txn.len(), 0);
7425                 node_txn.clear();
7426         }
7427         check_closed_broadcast!(nodes[0], true);
7428         check_added_monitors!(nodes[0], 1);
7429 }
7430
7431 #[test]
7432 fn test_bump_penalty_txn_on_remote_commitment() {
7433         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7434         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7435
7436         // Create 2 HTLCs
7437         // Provide preimage for one
7438         // Check aggregation
7439
7440         let chanmon_cfgs = create_chanmon_cfgs(2);
7441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7443         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7444
7445         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7446         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7447         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7448
7449         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7450         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7451         assert_eq!(remote_txn[0].output.len(), 4);
7452         assert_eq!(remote_txn[0].input.len(), 1);
7453         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7454
7455         // Claim a HTLC without revocation (provide B monitor with preimage)
7456         nodes[1].node.claim_funds(payment_preimage);
7457         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7458         mine_transaction(&nodes[1], &remote_txn[0]);
7459         check_added_monitors!(nodes[1], 2);
7460         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7461
7462         // One or more claim tx should have been broadcast, check it
7463         let timeout;
7464         let preimage;
7465         let preimage_bump;
7466         let feerate_timeout;
7467         let feerate_preimage;
7468         {
7469                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7470                 // 3 transactions including:
7471                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7472                 assert_eq!(node_txn.len(), 3);
7473                 assert_eq!(node_txn[0].input.len(), 1);
7474                 assert_eq!(node_txn[1].input.len(), 1);
7475                 assert_eq!(node_txn[2].input.len(), 1);
7476                 check_spends!(node_txn[0], remote_txn[0]);
7477                 check_spends!(node_txn[1], remote_txn[0]);
7478                 check_spends!(node_txn[2], remote_txn[0]);
7479
7480                 preimage = node_txn[0].txid();
7481                 let index = node_txn[0].input[0].previous_output.vout;
7482                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7483                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7484
7485                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7486                         (node_txn[2].clone(), node_txn[1].clone())
7487                 } else {
7488                         (node_txn[1].clone(), node_txn[2].clone())
7489                 };
7490
7491                 preimage_bump = preimage_bump_tx;
7492                 check_spends!(preimage_bump, remote_txn[0]);
7493                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7494
7495                 timeout = timeout_tx.txid();
7496                 let index = timeout_tx.input[0].previous_output.vout;
7497                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7498                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7499
7500                 node_txn.clear();
7501         };
7502         assert_ne!(feerate_timeout, 0);
7503         assert_ne!(feerate_preimage, 0);
7504
7505         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7506         connect_blocks(&nodes[1], 1);
7507         {
7508                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7509                 assert_eq!(node_txn.len(), 1);
7510                 assert_eq!(node_txn[0].input.len(), 1);
7511                 assert_eq!(preimage_bump.input.len(), 1);
7512                 check_spends!(node_txn[0], remote_txn[0]);
7513                 check_spends!(preimage_bump, remote_txn[0]);
7514
7515                 let index = preimage_bump.input[0].previous_output.vout;
7516                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7517                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7518                 assert!(new_feerate * 100 > feerate_timeout * 125);
7519                 assert_ne!(timeout, preimage_bump.txid());
7520
7521                 let index = node_txn[0].input[0].previous_output.vout;
7522                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7523                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7524                 assert!(new_feerate * 100 > feerate_preimage * 125);
7525                 assert_ne!(preimage, node_txn[0].txid());
7526
7527                 node_txn.clear();
7528         }
7529
7530         nodes[1].node.get_and_clear_pending_events();
7531         nodes[1].node.get_and_clear_pending_msg_events();
7532 }
7533
7534 #[test]
7535 fn test_counterparty_raa_skip_no_crash() {
7536         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7537         // commitment transaction, we would have happily carried on and provided them the next
7538         // commitment transaction based on one RAA forward. This would probably eventually have led to
7539         // channel closure, but it would not have resulted in funds loss. Still, our
7540         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7541         // check simply that the channel is closed in response to such an RAA, but don't check whether
7542         // we decide to punish our counterparty for revoking their funds (as we don't currently
7543         // implement that).
7544         let chanmon_cfgs = create_chanmon_cfgs(2);
7545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7548         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7549
7550         let per_commitment_secret;
7551         let next_per_commitment_point;
7552         {
7553                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7554                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7555                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7556
7557                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7558
7559                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7560                 keys.get_enforcement_state().last_holder_commitment -= 1;
7561                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7562
7563                 // Must revoke without gaps
7564                 keys.get_enforcement_state().last_holder_commitment -= 1;
7565                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7566
7567                 keys.get_enforcement_state().last_holder_commitment -= 1;
7568                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7569                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7570         }
7571
7572         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7573                 &msgs::RevokeAndACK {
7574                         channel_id,
7575                         per_commitment_secret,
7576                         next_per_commitment_point,
7577                         #[cfg(taproot)]
7578                         next_local_nonce: None,
7579                 });
7580         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7581         check_added_monitors!(nodes[1], 1);
7582         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7583 }
7584
7585 #[test]
7586 fn test_bump_txn_sanitize_tracking_maps() {
7587         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7588         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7589
7590         let chanmon_cfgs = create_chanmon_cfgs(2);
7591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7593         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7594
7595         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7596         // Lock HTLC in both directions
7597         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7598         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7599
7600         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7601         assert_eq!(revoked_local_txn[0].input.len(), 1);
7602         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7603
7604         // Revoke local commitment tx
7605         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7606
7607         // Broadcast set of revoked txn on A
7608         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7609         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7610         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7611
7612         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7613         check_closed_broadcast!(nodes[0], true);
7614         check_added_monitors!(nodes[0], 1);
7615         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7616         let penalty_txn = {
7617                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7618                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7619                 check_spends!(node_txn[0], revoked_local_txn[0]);
7620                 check_spends!(node_txn[1], revoked_local_txn[0]);
7621                 check_spends!(node_txn[2], revoked_local_txn[0]);
7622                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7623                 node_txn.clear();
7624                 penalty_txn
7625         };
7626         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7627         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7628         {
7629                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7630                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7631                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7632         }
7633 }
7634
7635 #[test]
7636 fn test_channel_conf_timeout() {
7637         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7638         // confirm within 2016 blocks, as recommended by BOLT 2.
7639         let chanmon_cfgs = create_chanmon_cfgs(2);
7640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7642         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7643
7644         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7645
7646         // The outbound node should wait forever for confirmation:
7647         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7648         // copied here instead of directly referencing the constant.
7649         connect_blocks(&nodes[0], 2016);
7650         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7651
7652         // The inbound node should fail the channel after exactly 2016 blocks
7653         connect_blocks(&nodes[1], 2015);
7654         check_added_monitors!(nodes[1], 0);
7655         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7656
7657         connect_blocks(&nodes[1], 1);
7658         check_added_monitors!(nodes[1], 1);
7659         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7660         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7661         assert_eq!(close_ev.len(), 1);
7662         match close_ev[0] {
7663                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7664                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7665                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7666                 },
7667                 _ => panic!("Unexpected event"),
7668         }
7669 }
7670
7671 #[test]
7672 fn test_override_channel_config() {
7673         let chanmon_cfgs = create_chanmon_cfgs(2);
7674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7676         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7677
7678         // Node0 initiates a channel to node1 using the override config.
7679         let mut override_config = UserConfig::default();
7680         override_config.channel_handshake_config.our_to_self_delay = 200;
7681
7682         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7683
7684         // Assert the channel created by node0 is using the override config.
7685         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7686         assert_eq!(res.channel_flags, 0);
7687         assert_eq!(res.to_self_delay, 200);
7688 }
7689
7690 #[test]
7691 fn test_override_0msat_htlc_minimum() {
7692         let mut zero_config = UserConfig::default();
7693         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7694         let chanmon_cfgs = create_chanmon_cfgs(2);
7695         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7696         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7697         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7698
7699         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7700         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7701         assert_eq!(res.htlc_minimum_msat, 1);
7702
7703         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7704         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7705         assert_eq!(res.htlc_minimum_msat, 1);
7706 }
7707
7708 #[test]
7709 fn test_channel_update_has_correct_htlc_maximum_msat() {
7710         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7711         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7712         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7713         // 90% of the `channel_value`.
7714         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7715
7716         let mut config_30_percent = UserConfig::default();
7717         config_30_percent.channel_handshake_config.announced_channel = true;
7718         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7719         let mut config_50_percent = UserConfig::default();
7720         config_50_percent.channel_handshake_config.announced_channel = true;
7721         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7722         let mut config_95_percent = UserConfig::default();
7723         config_95_percent.channel_handshake_config.announced_channel = true;
7724         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7725         let mut config_100_percent = UserConfig::default();
7726         config_100_percent.channel_handshake_config.announced_channel = true;
7727         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7728
7729         let chanmon_cfgs = create_chanmon_cfgs(4);
7730         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7731         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)]);
7732         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7733
7734         let channel_value_satoshis = 100000;
7735         let channel_value_msat = channel_value_satoshis * 1000;
7736         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7737         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7738         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7739
7740         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7741         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7742
7743         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7744         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7745         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7746         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7747         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7748         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7749
7750         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7751         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7752         // `channel_value`.
7753         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7754         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7755         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7756         // `channel_value`.
7757         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7758 }
7759
7760 #[test]
7761 fn test_manually_accept_inbound_channel_request() {
7762         let mut manually_accept_conf = UserConfig::default();
7763         manually_accept_conf.manually_accept_inbound_channels = true;
7764         let chanmon_cfgs = create_chanmon_cfgs(2);
7765         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7766         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7767         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7768
7769         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7770         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7771
7772         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7773
7774         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7775         // accepting the inbound channel request.
7776         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7777
7778         let events = nodes[1].node.get_and_clear_pending_events();
7779         match events[0] {
7780                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7781                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7782                 }
7783                 _ => panic!("Unexpected event"),
7784         }
7785
7786         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7787         assert_eq!(accept_msg_ev.len(), 1);
7788
7789         match accept_msg_ev[0] {
7790                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7791                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7792                 }
7793                 _ => panic!("Unexpected event"),
7794         }
7795
7796         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7797
7798         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7799         assert_eq!(close_msg_ev.len(), 1);
7800
7801         let events = nodes[1].node.get_and_clear_pending_events();
7802         match events[0] {
7803                 Event::ChannelClosed { user_channel_id, .. } => {
7804                         assert_eq!(user_channel_id, 23);
7805                 }
7806                 _ => panic!("Unexpected event"),
7807         }
7808 }
7809
7810 #[test]
7811 fn test_manually_reject_inbound_channel_request() {
7812         let mut manually_accept_conf = UserConfig::default();
7813         manually_accept_conf.manually_accept_inbound_channels = true;
7814         let chanmon_cfgs = create_chanmon_cfgs(2);
7815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7818
7819         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7820         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7821
7822         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7823
7824         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7825         // rejecting the inbound channel request.
7826         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7827
7828         let events = nodes[1].node.get_and_clear_pending_events();
7829         match events[0] {
7830                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7831                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7832                 }
7833                 _ => panic!("Unexpected event"),
7834         }
7835
7836         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7837         assert_eq!(close_msg_ev.len(), 1);
7838
7839         match close_msg_ev[0] {
7840                 MessageSendEvent::HandleError { ref node_id, .. } => {
7841                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7842                 }
7843                 _ => panic!("Unexpected event"),
7844         }
7845         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7846 }
7847
7848 #[test]
7849 fn test_reject_funding_before_inbound_channel_accepted() {
7850         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7851         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7852         // the node operator before the counterparty sends a `FundingCreated` message. If a
7853         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7854         // and the channel should be closed.
7855         let mut manually_accept_conf = UserConfig::default();
7856         manually_accept_conf.manually_accept_inbound_channels = true;
7857         let chanmon_cfgs = create_chanmon_cfgs(2);
7858         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7859         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7860         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7861
7862         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7863         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7864         let temp_channel_id = res.temporary_channel_id;
7865
7866         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7867
7868         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7869         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7870
7871         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7872         nodes[1].node.get_and_clear_pending_events();
7873
7874         // Get the `AcceptChannel` message of `nodes[1]` without calling
7875         // `ChannelManager::accept_inbound_channel`, which generates a
7876         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7877         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7878         // succeed when `nodes[0]` is passed to it.
7879         let accept_chan_msg = {
7880                 let mut node_1_per_peer_lock;
7881                 let mut node_1_peer_state_lock;
7882                 let channel =  get_inbound_v1_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7883                 channel.get_accept_channel_message()
7884         };
7885         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7886
7887         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7888
7889         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7890         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7891
7892         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7893         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7894
7895         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7896         assert_eq!(close_msg_ev.len(), 1);
7897
7898         let expected_err = "FundingCreated message received before the channel was accepted";
7899         match close_msg_ev[0] {
7900                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7901                         assert_eq!(msg.channel_id, temp_channel_id);
7902                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7903                         assert_eq!(msg.data, expected_err);
7904                 }
7905                 _ => panic!("Unexpected event"),
7906         }
7907
7908         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7909 }
7910
7911 #[test]
7912 fn test_can_not_accept_inbound_channel_twice() {
7913         let mut manually_accept_conf = UserConfig::default();
7914         manually_accept_conf.manually_accept_inbound_channels = true;
7915         let chanmon_cfgs = create_chanmon_cfgs(2);
7916         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7917         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7918         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7919
7920         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7921         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7922
7923         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7924
7925         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7926         // accepting the inbound channel request.
7927         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7928
7929         let events = nodes[1].node.get_and_clear_pending_events();
7930         match events[0] {
7931                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7932                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7933                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7934                         match api_res {
7935                                 Err(APIError::APIMisuseError { err }) => {
7936                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7937                                 },
7938                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7939                                 Err(_) => panic!("Unexpected Error"),
7940                         }
7941                 }
7942                 _ => panic!("Unexpected event"),
7943         }
7944
7945         // Ensure that the channel wasn't closed after attempting to accept it twice.
7946         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7947         assert_eq!(accept_msg_ev.len(), 1);
7948
7949         match accept_msg_ev[0] {
7950                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7951                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7952                 }
7953                 _ => panic!("Unexpected event"),
7954         }
7955 }
7956
7957 #[test]
7958 fn test_can_not_accept_unknown_inbound_channel() {
7959         let chanmon_cfg = create_chanmon_cfgs(2);
7960         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7961         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7962         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7963
7964         let unknown_channel_id = [0; 32];
7965         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7966         match api_res {
7967                 Err(APIError::ChannelUnavailable { err }) => {
7968                         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()));
7969                 },
7970                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7971                 Err(_) => panic!("Unexpected Error"),
7972         }
7973 }
7974
7975 #[test]
7976 fn test_onion_value_mpp_set_calculation() {
7977         // Test that we use the onion value `amt_to_forward` when
7978         // calculating whether we've reached the `total_msat` of an MPP
7979         // by having a routing node forward more than `amt_to_forward`
7980         // and checking that the receiving node doesn't generate
7981         // a PaymentClaimable event too early
7982         let node_count = 4;
7983         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7984         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7985         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7986         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7987
7988         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7989         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7990         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7991         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7992
7993         let total_msat = 100_000;
7994         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7995         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7996         let sample_path = route.paths.pop().unwrap();
7997
7998         let mut path_1 = sample_path.clone();
7999         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8000         path_1.hops[0].short_channel_id = chan_1_id;
8001         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8002         path_1.hops[1].short_channel_id = chan_3_id;
8003         path_1.hops[1].fee_msat = 100_000;
8004         route.paths.push(path_1);
8005
8006         let mut path_2 = sample_path.clone();
8007         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8008         path_2.hops[0].short_channel_id = chan_2_id;
8009         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8010         path_2.hops[1].short_channel_id = chan_4_id;
8011         path_2.hops[1].fee_msat = 1_000;
8012         route.paths.push(path_2);
8013
8014         // Send payment
8015         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8016         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8017                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8018         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8019                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8020         check_added_monitors!(nodes[0], expected_paths.len());
8021
8022         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8023         assert_eq!(events.len(), expected_paths.len());
8024
8025         // First path
8026         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8027         let mut payment_event = SendEvent::from_event(ev);
8028         let mut prev_node = &nodes[0];
8029
8030         for (idx, &node) in expected_paths[0].iter().enumerate() {
8031                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8032
8033                 if idx == 0 { // routing node
8034                         let session_priv = [3; 32];
8035                         let height = nodes[0].best_block_info().1;
8036                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8037                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8038                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8039                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8040                         // Edit amt_to_forward to simulate the sender having set
8041                         // the final amount and the routing node taking less fee
8042                         onion_payloads[1].amt_to_forward = 99_000;
8043                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8044                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8045                 }
8046
8047                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8048                 check_added_monitors!(node, 0);
8049                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8050                 expect_pending_htlcs_forwardable!(node);
8051
8052                 if idx == 0 {
8053                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8054                         assert_eq!(events_2.len(), 1);
8055                         check_added_monitors!(node, 1);
8056                         payment_event = SendEvent::from_event(events_2.remove(0));
8057                         assert_eq!(payment_event.msgs.len(), 1);
8058                 } else {
8059                         let events_2 = node.node.get_and_clear_pending_events();
8060                         assert!(events_2.is_empty());
8061                 }
8062
8063                 prev_node = node;
8064         }
8065
8066         // Second path
8067         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8068         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8069
8070         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8071 }
8072
8073 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8074
8075         let routing_node_count = msat_amounts.len();
8076         let node_count = routing_node_count + 2;
8077
8078         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8079         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8080         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8081         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8082
8083         let src_idx = 0;
8084         let dst_idx = 1;
8085
8086         // Create channels for each amount
8087         let mut expected_paths = Vec::with_capacity(routing_node_count);
8088         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8089         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8090         for i in 0..routing_node_count {
8091                 let routing_node = 2 + i;
8092                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8093                 src_chan_ids.push(src_chan_id);
8094                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8095                 dst_chan_ids.push(dst_chan_id);
8096                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8097                 expected_paths.push(path);
8098         }
8099         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8100
8101         // Create a route for each amount
8102         let example_amount = 100000;
8103         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);
8104         let sample_path = route.paths.pop().unwrap();
8105         for i in 0..routing_node_count {
8106                 let routing_node = 2 + i;
8107                 let mut path = sample_path.clone();
8108                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8109                 path.hops[0].short_channel_id = src_chan_ids[i];
8110                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8111                 path.hops[1].short_channel_id = dst_chan_ids[i];
8112                 path.hops[1].fee_msat = msat_amounts[i];
8113                 route.paths.push(path);
8114         }
8115
8116         // Send payment with manually set total_msat
8117         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8118         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8119                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8120         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8121                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8122         check_added_monitors!(nodes[src_idx], expected_paths.len());
8123
8124         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8125         assert_eq!(events.len(), expected_paths.len());
8126         let mut amount_received = 0;
8127         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8128                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8129
8130                 let current_path_amount = msat_amounts[path_idx];
8131                 amount_received += current_path_amount;
8132                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8133                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8134         }
8135
8136         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8137 }
8138
8139 #[test]
8140 fn test_overshoot_mpp() {
8141         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8142         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8143 }
8144
8145 #[test]
8146 fn test_simple_mpp() {
8147         // Simple test of sending a multi-path payment.
8148         let chanmon_cfgs = create_chanmon_cfgs(4);
8149         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8150         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8151         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8152
8153         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8154         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8155         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8156         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8157
8158         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8159         let path = route.paths[0].clone();
8160         route.paths.push(path);
8161         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8162         route.paths[0].hops[0].short_channel_id = chan_1_id;
8163         route.paths[0].hops[1].short_channel_id = chan_3_id;
8164         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8165         route.paths[1].hops[0].short_channel_id = chan_2_id;
8166         route.paths[1].hops[1].short_channel_id = chan_4_id;
8167         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8168         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8169 }
8170
8171 #[test]
8172 fn test_preimage_storage() {
8173         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8174         let chanmon_cfgs = create_chanmon_cfgs(2);
8175         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8176         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8177         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8178
8179         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8180
8181         {
8182                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8183                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8184                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8185                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8186                 check_added_monitors!(nodes[0], 1);
8187                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8188                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8189                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8190                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8191         }
8192         // Note that after leaving the above scope we have no knowledge of any arguments or return
8193         // values from previous calls.
8194         expect_pending_htlcs_forwardable!(nodes[1]);
8195         let events = nodes[1].node.get_and_clear_pending_events();
8196         assert_eq!(events.len(), 1);
8197         match events[0] {
8198                 Event::PaymentClaimable { ref purpose, .. } => {
8199                         match &purpose {
8200                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8201                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8202                                 },
8203                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8204                         }
8205                 },
8206                 _ => panic!("Unexpected event"),
8207         }
8208 }
8209
8210 #[test]
8211 fn test_bad_secret_hash() {
8212         // Simple test of unregistered payment hash/invalid payment secret handling
8213         let chanmon_cfgs = create_chanmon_cfgs(2);
8214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8216         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8217
8218         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8219
8220         let random_payment_hash = PaymentHash([42; 32]);
8221         let random_payment_secret = PaymentSecret([43; 32]);
8222         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8223         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8224
8225         // All the below cases should end up being handled exactly identically, so we macro the
8226         // resulting events.
8227         macro_rules! handle_unknown_invalid_payment_data {
8228                 ($payment_hash: expr) => {
8229                         check_added_monitors!(nodes[0], 1);
8230                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8231                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8232                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8233                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8234
8235                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8236                         // again to process the pending backwards-failure of the HTLC
8237                         expect_pending_htlcs_forwardable!(nodes[1]);
8238                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8239                         check_added_monitors!(nodes[1], 1);
8240
8241                         // We should fail the payment back
8242                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8243                         match events.pop().unwrap() {
8244                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8245                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8246                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8247                                 },
8248                                 _ => panic!("Unexpected event"),
8249                         }
8250                 }
8251         }
8252
8253         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8254         // Error data is the HTLC value (100,000) and current block height
8255         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8256
8257         // Send a payment with the right payment hash but the wrong payment secret
8258         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8259                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8260         handle_unknown_invalid_payment_data!(our_payment_hash);
8261         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8262
8263         // Send a payment with a random payment hash, but the right payment secret
8264         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8265                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8266         handle_unknown_invalid_payment_data!(random_payment_hash);
8267         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8268
8269         // Send a payment with a random payment hash and random payment secret
8270         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8271                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8272         handle_unknown_invalid_payment_data!(random_payment_hash);
8273         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8274 }
8275
8276 #[test]
8277 fn test_update_err_monitor_lockdown() {
8278         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8279         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8280         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8281         // error.
8282         //
8283         // This scenario may happen in a watchtower setup, where watchtower process a block height
8284         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8285         // commitment at same time.
8286
8287         let chanmon_cfgs = create_chanmon_cfgs(2);
8288         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8289         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8290         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8291
8292         // Create some initial channel
8293         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8294         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8295
8296         // Rebalance the network to generate htlc in the two directions
8297         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8298
8299         // Route a HTLC from node 0 to node 1 (but don't settle)
8300         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8301
8302         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8303         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8304         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8305         let persister = test_utils::TestPersister::new();
8306         let watchtower = {
8307                 let new_monitor = {
8308                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8309                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8310                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8311                         assert!(new_monitor == *monitor);
8312                         new_monitor
8313                 };
8314                 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);
8315                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8316                 watchtower
8317         };
8318         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8319         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8320         // transaction lock time requirements here.
8321         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8322         watchtower.chain_monitor.block_connected(&block, 200);
8323
8324         // Try to update ChannelMonitor
8325         nodes[1].node.claim_funds(preimage);
8326         check_added_monitors!(nodes[1], 1);
8327         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8328
8329         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8330         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8331         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8332         {
8333                 let mut node_0_per_peer_lock;
8334                 let mut node_0_peer_state_lock;
8335                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8336                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8337                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8338                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8339                 } else { assert!(false); }
8340         }
8341         // Our local monitor is in-sync and hasn't processed yet timeout
8342         check_added_monitors!(nodes[0], 1);
8343         let events = nodes[0].node.get_and_clear_pending_events();
8344         assert_eq!(events.len(), 1);
8345 }
8346
8347 #[test]
8348 fn test_concurrent_monitor_claim() {
8349         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8350         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8351         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8352         // state N+1 confirms. Alice claims output from state N+1.
8353
8354         let chanmon_cfgs = create_chanmon_cfgs(2);
8355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8357         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8358
8359         // Create some initial channel
8360         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8361         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8362
8363         // Rebalance the network to generate htlc in the two directions
8364         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8365
8366         // Route a HTLC from node 0 to node 1 (but don't settle)
8367         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8368
8369         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8370         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8371         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8372         let persister = test_utils::TestPersister::new();
8373         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8374                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8375         );
8376         let watchtower_alice = {
8377                 let new_monitor = {
8378                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8379                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8380                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8381                         assert!(new_monitor == *monitor);
8382                         new_monitor
8383                 };
8384                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8385                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8386                 watchtower
8387         };
8388         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8389         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8390         // requirements here.
8391         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8392         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8393         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8394
8395         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8396         let alice_state = {
8397                 let mut txn = alice_broadcaster.txn_broadcast();
8398                 assert_eq!(txn.len(), 2);
8399                 txn.remove(0)
8400         };
8401
8402         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8403         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8404         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8405         let persister = test_utils::TestPersister::new();
8406         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8407         let watchtower_bob = {
8408                 let new_monitor = {
8409                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8410                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8411                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8412                         assert!(new_monitor == *monitor);
8413                         new_monitor
8414                 };
8415                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8416                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8417                 watchtower
8418         };
8419         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8420
8421         // Route another payment to generate another update with still previous HTLC pending
8422         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8423         nodes[1].node.send_payment_with_route(&route, payment_hash,
8424                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8425         check_added_monitors!(nodes[1], 1);
8426
8427         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8428         assert_eq!(updates.update_add_htlcs.len(), 1);
8429         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8430         {
8431                 let mut node_0_per_peer_lock;
8432                 let mut node_0_peer_state_lock;
8433                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8434                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8435                         // Watchtower Alice should already have seen the block and reject the update
8436                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8437                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8438                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8439                 } else { assert!(false); }
8440         }
8441         // Our local monitor is in-sync and hasn't processed yet timeout
8442         check_added_monitors!(nodes[0], 1);
8443
8444         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8445         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8446
8447         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8448         let bob_state_y;
8449         {
8450                 let mut txn = bob_broadcaster.txn_broadcast();
8451                 assert_eq!(txn.len(), 2);
8452                 bob_state_y = txn.remove(0);
8453         };
8454
8455         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8456         let height = HTLC_TIMEOUT_BROADCAST + 1;
8457         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8458         check_closed_broadcast(&nodes[0], 1, true);
8459         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8460         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8461         check_added_monitors(&nodes[0], 1);
8462         {
8463                 let htlc_txn = alice_broadcaster.txn_broadcast();
8464                 assert_eq!(htlc_txn.len(), 2);
8465                 check_spends!(htlc_txn[0], bob_state_y);
8466                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8467                 // it. However, she should, because it now has an invalid parent.
8468                 check_spends!(htlc_txn[1], alice_state);
8469         }
8470 }
8471
8472 #[test]
8473 fn test_pre_lockin_no_chan_closed_update() {
8474         // Test that if a peer closes a channel in response to a funding_created message we don't
8475         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8476         // message).
8477         //
8478         // Doing so would imply a channel monitor update before the initial channel monitor
8479         // registration, violating our API guarantees.
8480         //
8481         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8482         // then opening a second channel with the same funding output as the first (which is not
8483         // rejected because the first channel does not exist in the ChannelManager) and closing it
8484         // before receiving funding_signed.
8485         let chanmon_cfgs = create_chanmon_cfgs(2);
8486         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8487         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8488         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8489
8490         // Create an initial channel
8491         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8492         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8493         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8494         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8495         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8496
8497         // Move the first channel through the funding flow...
8498         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8499
8500         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8501         check_added_monitors!(nodes[0], 0);
8502
8503         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8504         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8505         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8506         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8507         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8508 }
8509
8510 #[test]
8511 fn test_htlc_no_detection() {
8512         // This test is a mutation to underscore the detection logic bug we had
8513         // before #653. HTLC value routed is above the remaining balance, thus
8514         // inverting HTLC and `to_remote` output. HTLC will come second and
8515         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8516         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8517         // outputs order detection for correct spending children filtring.
8518
8519         let chanmon_cfgs = create_chanmon_cfgs(2);
8520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8522         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8523
8524         // Create some initial channels
8525         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8526
8527         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8528         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8529         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8530         assert_eq!(local_txn[0].input.len(), 1);
8531         assert_eq!(local_txn[0].output.len(), 3);
8532         check_spends!(local_txn[0], chan_1.3);
8533
8534         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8535         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8536         connect_block(&nodes[0], &block);
8537         // We deliberately connect the local tx twice as this should provoke a failure calling
8538         // this test before #653 fix.
8539         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8540         check_closed_broadcast!(nodes[0], true);
8541         check_added_monitors!(nodes[0], 1);
8542         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8543         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8544
8545         let htlc_timeout = {
8546                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8547                 assert_eq!(node_txn.len(), 1);
8548                 assert_eq!(node_txn[0].input.len(), 1);
8549                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8550                 check_spends!(node_txn[0], local_txn[0]);
8551                 node_txn[0].clone()
8552         };
8553
8554         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8555         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8556         expect_payment_failed!(nodes[0], our_payment_hash, false);
8557 }
8558
8559 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8560         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8561         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8562         // Carol, Alice would be the upstream node, and Carol the downstream.)
8563         //
8564         // Steps of the test:
8565         // 1) Alice sends a HTLC to Carol through Bob.
8566         // 2) Carol doesn't settle the HTLC.
8567         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8568         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8569         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8570         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8571         // 5) Carol release the preimage to Bob off-chain.
8572         // 6) Bob claims the offered output on the broadcasted commitment.
8573         let chanmon_cfgs = create_chanmon_cfgs(3);
8574         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8575         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8576         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8577
8578         // Create some initial channels
8579         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8580         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8581
8582         // Steps (1) and (2):
8583         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8584         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8585
8586         // Check that Alice's commitment transaction now contains an output for this HTLC.
8587         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8588         check_spends!(alice_txn[0], chan_ab.3);
8589         assert_eq!(alice_txn[0].output.len(), 2);
8590         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8591         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8592         assert_eq!(alice_txn.len(), 2);
8593
8594         // Steps (3) and (4):
8595         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8596         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8597         let mut force_closing_node = 0; // Alice force-closes
8598         let mut counterparty_node = 1; // Bob if Alice force-closes
8599
8600         // Bob force-closes
8601         if !broadcast_alice {
8602                 force_closing_node = 1;
8603                 counterparty_node = 0;
8604         }
8605         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8606         check_closed_broadcast!(nodes[force_closing_node], true);
8607         check_added_monitors!(nodes[force_closing_node], 1);
8608         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8609         if go_onchain_before_fulfill {
8610                 let txn_to_broadcast = match broadcast_alice {
8611                         true => alice_txn.clone(),
8612                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8613                 };
8614                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8615                 if broadcast_alice {
8616                         check_closed_broadcast!(nodes[1], true);
8617                         check_added_monitors!(nodes[1], 1);
8618                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8619                 }
8620         }
8621
8622         // Step (5):
8623         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8624         // process of removing the HTLC from their commitment transactions.
8625         nodes[2].node.claim_funds(payment_preimage);
8626         check_added_monitors!(nodes[2], 1);
8627         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8628
8629         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8630         assert!(carol_updates.update_add_htlcs.is_empty());
8631         assert!(carol_updates.update_fail_htlcs.is_empty());
8632         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8633         assert!(carol_updates.update_fee.is_none());
8634         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8635
8636         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8637         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8638         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8639         if !go_onchain_before_fulfill && broadcast_alice {
8640                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8641                 assert_eq!(events.len(), 1);
8642                 match events[0] {
8643                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8644                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8645                         },
8646                         _ => panic!("Unexpected event"),
8647                 };
8648         }
8649         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8650         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8651         // Carol<->Bob's updated commitment transaction info.
8652         check_added_monitors!(nodes[1], 2);
8653
8654         let events = nodes[1].node.get_and_clear_pending_msg_events();
8655         assert_eq!(events.len(), 2);
8656         let bob_revocation = match events[0] {
8657                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8658                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8659                         (*msg).clone()
8660                 },
8661                 _ => panic!("Unexpected event"),
8662         };
8663         let bob_updates = match events[1] {
8664                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8665                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8666                         (*updates).clone()
8667                 },
8668                 _ => panic!("Unexpected event"),
8669         };
8670
8671         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8672         check_added_monitors!(nodes[2], 1);
8673         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8674         check_added_monitors!(nodes[2], 1);
8675
8676         let events = nodes[2].node.get_and_clear_pending_msg_events();
8677         assert_eq!(events.len(), 1);
8678         let carol_revocation = match events[0] {
8679                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8680                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8681                         (*msg).clone()
8682                 },
8683                 _ => panic!("Unexpected event"),
8684         };
8685         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8686         check_added_monitors!(nodes[1], 1);
8687
8688         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8689         // here's where we put said channel's commitment tx on-chain.
8690         let mut txn_to_broadcast = alice_txn.clone();
8691         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8692         if !go_onchain_before_fulfill {
8693                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8694                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8695                 if broadcast_alice {
8696                         check_closed_broadcast!(nodes[1], true);
8697                         check_added_monitors!(nodes[1], 1);
8698                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8699                 }
8700                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8701                 if broadcast_alice {
8702                         assert_eq!(bob_txn.len(), 1);
8703                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8704                 } else {
8705                         assert_eq!(bob_txn.len(), 2);
8706                         check_spends!(bob_txn[0], chan_ab.3);
8707                 }
8708         }
8709
8710         // Step (6):
8711         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8712         // broadcasted commitment transaction.
8713         {
8714                 let script_weight = match broadcast_alice {
8715                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8716                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8717                 };
8718                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8719                 // Bob force-closed and broadcasts the commitment transaction along with a
8720                 // HTLC-output-claiming transaction.
8721                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8722                 if broadcast_alice {
8723                         assert_eq!(bob_txn.len(), 1);
8724                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8725                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8726                 } else {
8727                         assert_eq!(bob_txn.len(), 2);
8728                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8729                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8730                 }
8731         }
8732 }
8733
8734 #[test]
8735 fn test_onchain_htlc_settlement_after_close() {
8736         do_test_onchain_htlc_settlement_after_close(true, true);
8737         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8738         do_test_onchain_htlc_settlement_after_close(true, false);
8739         do_test_onchain_htlc_settlement_after_close(false, false);
8740 }
8741
8742 #[test]
8743 fn test_duplicate_temporary_channel_id_from_different_peers() {
8744         // Tests that we can accept two different `OpenChannel` requests with the same
8745         // `temporary_channel_id`, as long as they are from different peers.
8746         let chanmon_cfgs = create_chanmon_cfgs(3);
8747         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8748         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8749         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8750
8751         // Create an first channel channel
8752         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8753         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8754
8755         // Create an second channel
8756         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8757         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8758
8759         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8760         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8761         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8762
8763         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8764         // `temporary_channel_id` as they are from different peers.
8765         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8766         {
8767                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8768                 assert_eq!(events.len(), 1);
8769                 match &events[0] {
8770                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8771                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8772                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8773                         },
8774                         _ => panic!("Unexpected event"),
8775                 }
8776         }
8777
8778         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8779         {
8780                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8781                 assert_eq!(events.len(), 1);
8782                 match &events[0] {
8783                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8784                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8785                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8786                         },
8787                         _ => panic!("Unexpected event"),
8788                 }
8789         }
8790 }
8791
8792 #[test]
8793 fn test_duplicate_chan_id() {
8794         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8795         // already open we reject it and keep the old channel.
8796         //
8797         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8798         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8799         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8800         // updating logic for the existing channel.
8801         let chanmon_cfgs = create_chanmon_cfgs(2);
8802         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8803         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8804         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8805
8806         // Create an initial channel
8807         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8808         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8809         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8810         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()));
8811
8812         // Try to create a second channel with the same temporary_channel_id as the first and check
8813         // that it is rejected.
8814         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8815         {
8816                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8817                 assert_eq!(events.len(), 1);
8818                 match events[0] {
8819                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8820                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8821                                 // first (valid) and second (invalid) channels are closed, given they both have
8822                                 // the same non-temporary channel_id. However, currently we do not, so we just
8823                                 // move forward with it.
8824                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8825                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8826                         },
8827                         _ => panic!("Unexpected event"),
8828                 }
8829         }
8830
8831         // Move the first channel through the funding flow...
8832         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8833
8834         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8835         check_added_monitors!(nodes[0], 0);
8836
8837         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8838         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8839         {
8840                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8841                 assert_eq!(added_monitors.len(), 1);
8842                 assert_eq!(added_monitors[0].0, funding_output);
8843                 added_monitors.clear();
8844         }
8845         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8846
8847         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8848
8849         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8850         let channel_id = funding_outpoint.to_channel_id();
8851
8852         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8853         // temporary one).
8854
8855         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8856         // Technically this is allowed by the spec, but we don't support it and there's little reason
8857         // to. Still, it shouldn't cause any other issues.
8858         open_chan_msg.temporary_channel_id = channel_id;
8859         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8860         {
8861                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8862                 assert_eq!(events.len(), 1);
8863                 match events[0] {
8864                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8865                                 // Technically, at this point, nodes[1] would be justified in thinking both
8866                                 // channels are closed, but currently we do not, so we just move forward with it.
8867                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8868                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8869                         },
8870                         _ => panic!("Unexpected event"),
8871                 }
8872         }
8873
8874         // Now try to create a second channel which has a duplicate funding output.
8875         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8876         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8877         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8878         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()));
8879         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8880
8881         let (_, funding_created) = {
8882                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8883                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8884                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8885                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8886                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8887                 // channelmanager in a possibly nonsense state instead).
8888                 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8889                 let logger = test_utils::TestLogger::new();
8890                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8891         };
8892         check_added_monitors!(nodes[0], 0);
8893         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8894         // At this point we'll look up if the channel_id is present and immediately fail the channel
8895         // without trying to persist the `ChannelMonitor`.
8896         check_added_monitors!(nodes[1], 0);
8897
8898         // ...still, nodes[1] will reject the duplicate channel.
8899         {
8900                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8901                 assert_eq!(events.len(), 1);
8902                 match events[0] {
8903                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8904                                 // Technically, at this point, nodes[1] would be justified in thinking both
8905                                 // channels are closed, but currently we do not, so we just move forward with it.
8906                                 assert_eq!(msg.channel_id, channel_id);
8907                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8908                         },
8909                         _ => panic!("Unexpected event"),
8910                 }
8911         }
8912
8913         // finally, finish creating the original channel and send a payment over it to make sure
8914         // everything is functional.
8915         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8916         {
8917                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8918                 assert_eq!(added_monitors.len(), 1);
8919                 assert_eq!(added_monitors[0].0, funding_output);
8920                 added_monitors.clear();
8921         }
8922         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8923
8924         let events_4 = nodes[0].node.get_and_clear_pending_events();
8925         assert_eq!(events_4.len(), 0);
8926         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8927         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8928
8929         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8930         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8931         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8932
8933         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8934 }
8935
8936 #[test]
8937 fn test_error_chans_closed() {
8938         // Test that we properly handle error messages, closing appropriate channels.
8939         //
8940         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8941         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8942         // we can test various edge cases around it to ensure we don't regress.
8943         let chanmon_cfgs = create_chanmon_cfgs(3);
8944         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8945         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8946         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8947
8948         // Create some initial channels
8949         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8950         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8951         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8952
8953         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8954         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8955         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8956
8957         // Closing a channel from a different peer has no effect
8958         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8959         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8960
8961         // Closing one channel doesn't impact others
8962         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8963         check_added_monitors!(nodes[0], 1);
8964         check_closed_broadcast!(nodes[0], false);
8965         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8966         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8967         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8968         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);
8969         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);
8970
8971         // A null channel ID should close all channels
8972         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8973         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8974         check_added_monitors!(nodes[0], 2);
8975         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8976         let events = nodes[0].node.get_and_clear_pending_msg_events();
8977         assert_eq!(events.len(), 2);
8978         match events[0] {
8979                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8980                         assert_eq!(msg.contents.flags & 2, 2);
8981                 },
8982                 _ => panic!("Unexpected event"),
8983         }
8984         match events[1] {
8985                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8986                         assert_eq!(msg.contents.flags & 2, 2);
8987                 },
8988                 _ => panic!("Unexpected event"),
8989         }
8990         // Note that at this point users of a standard PeerHandler will end up calling
8991         // peer_disconnected.
8992         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8993         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8994
8995         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8996         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8997         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8998 }
8999
9000 #[test]
9001 fn test_invalid_funding_tx() {
9002         // Test that we properly handle invalid funding transactions sent to us from a peer.
9003         //
9004         // Previously, all other major lightning implementations had failed to properly sanitize
9005         // funding transactions from their counterparties, leading to a multi-implementation critical
9006         // security vulnerability (though we always sanitized properly, we've previously had
9007         // un-released crashes in the sanitization process).
9008         //
9009         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9010         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9011         // gave up on it. We test this here by generating such a transaction.
9012         let chanmon_cfgs = create_chanmon_cfgs(2);
9013         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9014         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9015         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9016
9017         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9018         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()));
9019         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()));
9020
9021         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9022
9023         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9024         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9025         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9026         // its length.
9027         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9028         let wit_program_script: Script = wit_program.into();
9029         for output in tx.output.iter_mut() {
9030                 // Make the confirmed funding transaction have a bogus script_pubkey
9031                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9032         }
9033
9034         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9035         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()));
9036         check_added_monitors!(nodes[1], 1);
9037         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9038
9039         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()));
9040         check_added_monitors!(nodes[0], 1);
9041         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9042
9043         let events_1 = nodes[0].node.get_and_clear_pending_events();
9044         assert_eq!(events_1.len(), 0);
9045
9046         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9047         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9048         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9049
9050         let expected_err = "funding tx had wrong script/value or output index";
9051         confirm_transaction_at(&nodes[1], &tx, 1);
9052         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9053         check_added_monitors!(nodes[1], 1);
9054         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9055         assert_eq!(events_2.len(), 1);
9056         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9057                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9058                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9059                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9060                 } else { panic!(); }
9061         } else { panic!(); }
9062         assert_eq!(nodes[1].node.list_channels().len(), 0);
9063
9064         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9065         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9066         // as its not 32 bytes long.
9067         let mut spend_tx = Transaction {
9068                 version: 2i32, lock_time: PackedLockTime::ZERO,
9069                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9070                         previous_output: BitcoinOutPoint {
9071                                 txid: tx.txid(),
9072                                 vout: idx as u32,
9073                         },
9074                         script_sig: Script::new(),
9075                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9076                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9077                 }).collect(),
9078                 output: vec![TxOut {
9079                         value: 1000,
9080                         script_pubkey: Script::new(),
9081                 }]
9082         };
9083         check_spends!(spend_tx, tx);
9084         mine_transaction(&nodes[1], &spend_tx);
9085 }
9086
9087 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9088         // In the first version of the chain::Confirm interface, after a refactor was made to not
9089         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9090         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9091         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9092         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9093         // spending transaction until height N+1 (or greater). This was due to the way
9094         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9095         // spending transaction at the height the input transaction was confirmed at, not whether we
9096         // should broadcast a spending transaction at the current height.
9097         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9098         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9099         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9100         // until we learned about an additional block.
9101         //
9102         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9103         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9104         let chanmon_cfgs = create_chanmon_cfgs(3);
9105         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9106         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9107         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9108         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9109
9110         create_announced_chan_between_nodes(&nodes, 0, 1);
9111         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9112         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9113         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9114         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9115
9116         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9117         check_closed_broadcast!(nodes[1], true);
9118         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9119         check_added_monitors!(nodes[1], 1);
9120         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9121         assert_eq!(node_txn.len(), 1);
9122
9123         let conf_height = nodes[1].best_block_info().1;
9124         if !test_height_before_timelock {
9125                 connect_blocks(&nodes[1], 24 * 6);
9126         }
9127         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9128                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9129         if test_height_before_timelock {
9130                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9131                 // generate any events or broadcast any transactions
9132                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9133                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9134         } else {
9135                 // We should broadcast an HTLC transaction spending our funding transaction first
9136                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9137                 assert_eq!(spending_txn.len(), 2);
9138                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9139                 check_spends!(spending_txn[1], node_txn[0]);
9140                 // We should also generate a SpendableOutputs event with the to_self output (as its
9141                 // timelock is up).
9142                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9143                 assert_eq!(descriptor_spend_txn.len(), 1);
9144
9145                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9146                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9147                 // additional block built on top of the current chain.
9148                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9149                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9150                 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 }]);
9151                 check_added_monitors!(nodes[1], 1);
9152
9153                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9154                 assert!(updates.update_add_htlcs.is_empty());
9155                 assert!(updates.update_fulfill_htlcs.is_empty());
9156                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9157                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9158                 assert!(updates.update_fee.is_none());
9159                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9160                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9161                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9162         }
9163 }
9164
9165 #[test]
9166 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9167         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9168         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9169 }
9170
9171 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9172         let chanmon_cfgs = create_chanmon_cfgs(2);
9173         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9174         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9175         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9176
9177         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9178
9179         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9180                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9181         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9182
9183         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9184
9185         {
9186                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9187                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9188                 check_added_monitors!(nodes[0], 1);
9189                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9190                 assert_eq!(events.len(), 1);
9191                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9192                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9193                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9194         }
9195         expect_pending_htlcs_forwardable!(nodes[1]);
9196         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9197
9198         {
9199                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9200                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9201                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9202                 check_added_monitors!(nodes[0], 1);
9203                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9204                 assert_eq!(events.len(), 1);
9205                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9206                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9207                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9208                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9209                 // assume the second is a privacy attack (no longer particularly relevant
9210                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9211                 // the first HTLC delivered above.
9212         }
9213
9214         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9215         nodes[1].node.process_pending_htlc_forwards();
9216
9217         if test_for_second_fail_panic {
9218                 // Now we go fail back the first HTLC from the user end.
9219                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9220
9221                 let expected_destinations = vec![
9222                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9223                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9224                 ];
9225                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9226                 nodes[1].node.process_pending_htlc_forwards();
9227
9228                 check_added_monitors!(nodes[1], 1);
9229                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9230                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9231
9232                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9233                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9234                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9235
9236                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9237                 assert_eq!(failure_events.len(), 4);
9238                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9239                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9240                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9241                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9242         } else {
9243                 // Let the second HTLC fail and claim the first
9244                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9245                 nodes[1].node.process_pending_htlc_forwards();
9246
9247                 check_added_monitors!(nodes[1], 1);
9248                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9249                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9250                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9251
9252                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9253
9254                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9255         }
9256 }
9257
9258 #[test]
9259 fn test_dup_htlc_second_fail_panic() {
9260         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9261         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9262         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9263         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9264         do_test_dup_htlc_second_rejected(true);
9265 }
9266
9267 #[test]
9268 fn test_dup_htlc_second_rejected() {
9269         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9270         // simply reject the second HTLC but are still able to claim the first HTLC.
9271         do_test_dup_htlc_second_rejected(false);
9272 }
9273
9274 #[test]
9275 fn test_inconsistent_mpp_params() {
9276         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9277         // such HTLC and allow the second to stay.
9278         let chanmon_cfgs = create_chanmon_cfgs(4);
9279         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9280         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9281         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9282
9283         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9284         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9285         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9286         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9287
9288         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9289                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9290         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9291         assert_eq!(route.paths.len(), 2);
9292         route.paths.sort_by(|path_a, _| {
9293                 // Sort the path so that the path through nodes[1] comes first
9294                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9295                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9296         });
9297
9298         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9299
9300         let cur_height = nodes[0].best_block_info().1;
9301         let payment_id = PaymentId([42; 32]);
9302
9303         let session_privs = {
9304                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9305                 // ultimately have, just not right away.
9306                 let mut dup_route = route.clone();
9307                 dup_route.paths.push(route.paths[1].clone());
9308                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9309                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9310         };
9311         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9312                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9313                 &None, session_privs[0]).unwrap();
9314         check_added_monitors!(nodes[0], 1);
9315
9316         {
9317                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9318                 assert_eq!(events.len(), 1);
9319                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9320         }
9321         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9322
9323         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9324                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9325         check_added_monitors!(nodes[0], 1);
9326
9327         {
9328                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9329                 assert_eq!(events.len(), 1);
9330                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9331
9332                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9333                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9334
9335                 expect_pending_htlcs_forwardable!(nodes[2]);
9336                 check_added_monitors!(nodes[2], 1);
9337
9338                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9339                 assert_eq!(events.len(), 1);
9340                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9341
9342                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9343                 check_added_monitors!(nodes[3], 0);
9344                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9345
9346                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9347                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9348                 // post-payment_secrets) and fail back the new HTLC.
9349         }
9350         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9351         nodes[3].node.process_pending_htlc_forwards();
9352         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9353         nodes[3].node.process_pending_htlc_forwards();
9354
9355         check_added_monitors!(nodes[3], 1);
9356
9357         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9358         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9359         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9360
9361         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 }]);
9362         check_added_monitors!(nodes[2], 1);
9363
9364         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9365         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9366         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9367
9368         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9369
9370         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9371                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9372                 &None, session_privs[2]).unwrap();
9373         check_added_monitors!(nodes[0], 1);
9374
9375         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9376         assert_eq!(events.len(), 1);
9377         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9378
9379         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9380         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9381 }
9382
9383 #[test]
9384 fn test_keysend_payments_to_public_node() {
9385         let chanmon_cfgs = create_chanmon_cfgs(2);
9386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9389
9390         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9391         let network_graph = nodes[0].network_graph.clone();
9392         let payer_pubkey = nodes[0].node.get_our_node_id();
9393         let payee_pubkey = nodes[1].node.get_our_node_id();
9394         let route_params = RouteParameters {
9395                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9396                 final_value_msat: 10000,
9397         };
9398         let scorer = test_utils::TestScorer::new();
9399         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9400         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9401
9402         let test_preimage = PaymentPreimage([42; 32]);
9403         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9404                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9405         check_added_monitors!(nodes[0], 1);
9406         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9407         assert_eq!(events.len(), 1);
9408         let event = events.pop().unwrap();
9409         let path = vec![&nodes[1]];
9410         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9411         claim_payment(&nodes[0], &path, test_preimage);
9412 }
9413
9414 #[test]
9415 fn test_keysend_payments_to_private_node() {
9416         let chanmon_cfgs = create_chanmon_cfgs(2);
9417         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9418         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9419         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9420
9421         let payer_pubkey = nodes[0].node.get_our_node_id();
9422         let payee_pubkey = nodes[1].node.get_our_node_id();
9423
9424         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9425         let route_params = RouteParameters {
9426                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9427                 final_value_msat: 10000,
9428         };
9429         let network_graph = nodes[0].network_graph.clone();
9430         let first_hops = nodes[0].node.list_usable_channels();
9431         let scorer = test_utils::TestScorer::new();
9432         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9433         let route = find_route(
9434                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9435                 nodes[0].logger, &scorer, &(), &random_seed_bytes
9436         ).unwrap();
9437
9438         let test_preimage = PaymentPreimage([42; 32]);
9439         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9440                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9441         check_added_monitors!(nodes[0], 1);
9442         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9443         assert_eq!(events.len(), 1);
9444         let event = events.pop().unwrap();
9445         let path = vec![&nodes[1]];
9446         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9447         claim_payment(&nodes[0], &path, test_preimage);
9448 }
9449
9450 #[test]
9451 fn test_double_partial_claim() {
9452         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9453         // time out, the sender resends only some of the MPP parts, then the user processes the
9454         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9455         // amount.
9456         let chanmon_cfgs = create_chanmon_cfgs(4);
9457         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9458         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9459         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9460
9461         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9462         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9463         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9464         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9465
9466         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9467         assert_eq!(route.paths.len(), 2);
9468         route.paths.sort_by(|path_a, _| {
9469                 // Sort the path so that the path through nodes[1] comes first
9470                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9471                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9472         });
9473
9474         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9475         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9476         // amount of time to respond to.
9477
9478         // Connect some blocks to time out the payment
9479         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9480         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9481
9482         let failed_destinations = vec![
9483                 HTLCDestination::FailedPayment { payment_hash },
9484                 HTLCDestination::FailedPayment { payment_hash },
9485         ];
9486         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9487
9488         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9489
9490         // nodes[1] now retries one of the two paths...
9491         nodes[0].node.send_payment_with_route(&route, payment_hash,
9492                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9493         check_added_monitors!(nodes[0], 2);
9494
9495         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9496         assert_eq!(events.len(), 2);
9497         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9498         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9499
9500         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9501         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9502         nodes[3].node.claim_funds(payment_preimage);
9503         check_added_monitors!(nodes[3], 0);
9504         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9505 }
9506
9507 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9508 #[derive(Clone, Copy, PartialEq)]
9509 enum ExposureEvent {
9510         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9511         AtHTLCForward,
9512         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9513         AtHTLCReception,
9514         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9515         AtUpdateFeeOutbound,
9516 }
9517
9518 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9519         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9520         // policy.
9521         //
9522         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9523         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9524         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9525         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9526         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9527         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9528         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9529         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9530
9531         let chanmon_cfgs = create_chanmon_cfgs(2);
9532         let mut config = test_default_channel_config();
9533         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9534                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9535                 // to get roughly the same initial value as the default setting when this test was
9536                 // originally written.
9537                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9538         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9541         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9542
9543         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9544         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9545         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9546         open_channel.max_accepted_htlcs = 60;
9547         if on_holder_tx {
9548                 open_channel.dust_limit_satoshis = 546;
9549         }
9550         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9551         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9552         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9553
9554         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9555
9556         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9557
9558         if on_holder_tx {
9559                 let mut node_0_per_peer_lock;
9560                 let mut node_0_peer_state_lock;
9561                 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);
9562                 chan.context.holder_dust_limit_satoshis = 546;
9563         }
9564
9565         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9566         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()));
9567         check_added_monitors!(nodes[1], 1);
9568         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9569
9570         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()));
9571         check_added_monitors!(nodes[0], 1);
9572         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9573
9574         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9575         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9576         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9577
9578         // Fetch a route in advance as we will be unable to once we're unable to send.
9579         let (mut route, payment_hash, _, payment_secret) =
9580                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9581
9582         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9583                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9584                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9585                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9586                 (chan.context.get_dust_buffer_feerate(None) as u64,
9587                 chan.context.get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9588         };
9589         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9590         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9591
9592         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9593         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9594
9595         let dust_htlc_on_counterparty_tx: u64 = 4;
9596         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9597
9598         if on_holder_tx {
9599                 if dust_outbound_balance {
9600                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9601                         // Outbound dust balance: 4372 sats
9602                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9603                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9604                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9605                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9606                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9607                         }
9608                 } else {
9609                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9610                         // Inbound dust balance: 4372 sats
9611                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9612                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9613                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9614                         }
9615                 }
9616         } else {
9617                 if dust_outbound_balance {
9618                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9619                         // Outbound dust balance: 5000 sats
9620                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9621                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9622                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9623                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9624                         }
9625                 } else {
9626                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9627                         // Inbound dust balance: 5000 sats
9628                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9629                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9630                         }
9631                 }
9632         }
9633
9634         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9635                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9636                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9637                 // With default dust exposure: 5000 sats
9638                 if on_holder_tx {
9639                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9640                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9641                                 ), true, APIError::ChannelUnavailable { .. }, {});
9642                 } else {
9643                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9644                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9645                                 ), true, APIError::ChannelUnavailable { .. }, {});
9646                 }
9647         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9648                 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 + 4 });
9649                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9650                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9651                 check_added_monitors!(nodes[1], 1);
9652                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9653                 assert_eq!(events.len(), 1);
9654                 let payment_event = SendEvent::from_event(events.remove(0));
9655                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9656                 // With default dust exposure: 5000 sats
9657                 if on_holder_tx {
9658                         // Outbound dust balance: 6399 sats
9659                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9660                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9661                         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 }, max_dust_htlc_exposure_msat), 1);
9662                 } else {
9663                         // Outbound dust balance: 5200 sats
9664                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9665                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9666                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9667                                         max_dust_htlc_exposure_msat), 1);
9668                 }
9669         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9670                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9671                 // For the multiplier dust exposure limit, since it scales with feerate,
9672                 // we need to add a lot of HTLCs that will become dust at the new feerate
9673                 // to cross the threshold.
9674                 for _ in 0..20 {
9675                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9676                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9677                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9678                 }
9679                 {
9680                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9681                         *feerate_lock = *feerate_lock * 10;
9682                 }
9683                 nodes[0].node.timer_tick_occurred();
9684                 check_added_monitors!(nodes[0], 1);
9685                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9686         }
9687
9688         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9689         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9690         added_monitors.clear();
9691 }
9692
9693 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9694         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9695         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9696         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9697         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9698         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9699         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9700         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9701         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9702         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9703         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9704         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9705         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9706 }
9707
9708 #[test]
9709 fn test_max_dust_htlc_exposure() {
9710         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9711         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9712 }
9713
9714 #[test]
9715 fn test_non_final_funding_tx() {
9716         let chanmon_cfgs = create_chanmon_cfgs(2);
9717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9719         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9720
9721         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9722         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9723         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9724         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9725         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9726
9727         let best_height = nodes[0].node.best_block.read().unwrap().height();
9728
9729         let chan_id = *nodes[0].network_chan_count.borrow();
9730         let events = nodes[0].node.get_and_clear_pending_events();
9731         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9732         assert_eq!(events.len(), 1);
9733         let mut tx = match events[0] {
9734                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9735                         // Timelock the transaction _beyond_ the best client height + 1.
9736                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9737                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9738                         }]}
9739                 },
9740                 _ => panic!("Unexpected event"),
9741         };
9742         // Transaction should fail as it's evaluated as non-final for propagation.
9743         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9744                 Err(APIError::APIMisuseError { err }) => {
9745                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9746                 },
9747                 _ => panic!()
9748         }
9749
9750         // However, transaction should be accepted if it's in a +1 headroom from best block.
9751         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9752         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9753         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9754 }
9755
9756 #[test]
9757 fn accept_busted_but_better_fee() {
9758         // If a peer sends us a fee update that is too low, but higher than our previous channel
9759         // feerate, we should accept it. In the future we may want to consider closing the channel
9760         // later, but for now we only accept the update.
9761         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9764         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9765
9766         create_chan_between_nodes(&nodes[0], &nodes[1]);
9767
9768         // Set nodes[1] to expect 5,000 sat/kW.
9769         {
9770                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9771                 *feerate_lock = 5000;
9772         }
9773
9774         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9775         {
9776                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9777                 *feerate_lock = 1000;
9778         }
9779         nodes[0].node.timer_tick_occurred();
9780         check_added_monitors!(nodes[0], 1);
9781
9782         let events = nodes[0].node.get_and_clear_pending_msg_events();
9783         assert_eq!(events.len(), 1);
9784         match events[0] {
9785                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9786                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9787                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9788                 },
9789                 _ => panic!("Unexpected event"),
9790         };
9791
9792         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9793         // it.
9794         {
9795                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9796                 *feerate_lock = 2000;
9797         }
9798         nodes[0].node.timer_tick_occurred();
9799         check_added_monitors!(nodes[0], 1);
9800
9801         let events = nodes[0].node.get_and_clear_pending_msg_events();
9802         assert_eq!(events.len(), 1);
9803         match events[0] {
9804                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9805                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9806                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9807                 },
9808                 _ => panic!("Unexpected event"),
9809         };
9810
9811         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9812         // channel.
9813         {
9814                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9815                 *feerate_lock = 1000;
9816         }
9817         nodes[0].node.timer_tick_occurred();
9818         check_added_monitors!(nodes[0], 1);
9819
9820         let events = nodes[0].node.get_and_clear_pending_msg_events();
9821         assert_eq!(events.len(), 1);
9822         match events[0] {
9823                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9824                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9825                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9826                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9827                         check_closed_broadcast!(nodes[1], true);
9828                         check_added_monitors!(nodes[1], 1);
9829                 },
9830                 _ => panic!("Unexpected event"),
9831         };
9832 }
9833
9834 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9835         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9836         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9837         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9838         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9839         let min_final_cltv_expiry_delta = 120;
9840         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9841                 min_final_cltv_expiry_delta - 2 };
9842         let recv_value = 100_000;
9843
9844         create_chan_between_nodes(&nodes[0], &nodes[1]);
9845
9846         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9847         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9848                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9849                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9850                 (payment_hash, payment_preimage, payment_secret)
9851         } else {
9852                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9853                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9854         };
9855         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9856         nodes[0].node.send_payment_with_route(&route, payment_hash,
9857                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9858         check_added_monitors!(nodes[0], 1);
9859         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9860         assert_eq!(events.len(), 1);
9861         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9862         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9863         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9864         expect_pending_htlcs_forwardable!(nodes[1]);
9865
9866         if valid_delta {
9867                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9868                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9869
9870                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9871         } else {
9872                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9873
9874                 check_added_monitors!(nodes[1], 1);
9875
9876                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9877                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9878                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9879
9880                 expect_payment_failed!(nodes[0], payment_hash, true);
9881         }
9882 }
9883
9884 #[test]
9885 fn test_payment_with_custom_min_cltv_expiry_delta() {
9886         do_payment_with_custom_min_final_cltv_expiry(false, false);
9887         do_payment_with_custom_min_final_cltv_expiry(false, true);
9888         do_payment_with_custom_min_final_cltv_expiry(true, false);
9889         do_payment_with_custom_min_final_cltv_expiry(true, true);
9890 }
9891
9892 #[test]
9893 fn test_disconnects_peer_awaiting_response_ticks() {
9894         // Tests that nodes which are awaiting on a response critical for channel responsiveness
9895         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9896         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9897         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9898         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9899         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9900
9901         // Asserts a disconnect event is queued to the user.
9902         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9903                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9904                         if let MessageSendEvent::HandleError { action, .. } = event {
9905                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9906                                         Some(())
9907                                 } else {
9908                                         None
9909                                 }
9910                         } else {
9911                                 None
9912                         }
9913                 );
9914                 assert_eq!(disconnect_event.is_some(), should_disconnect);
9915         };
9916
9917         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9918         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9919         let check_disconnect = |node: &Node| {
9920                 // No disconnect without any timer ticks.
9921                 check_disconnect_event(node, false);
9922
9923                 // No disconnect with 1 timer tick less than required.
9924                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9925                         node.node.timer_tick_occurred();
9926                         check_disconnect_event(node, false);
9927                 }
9928
9929                 // Disconnect after reaching the required ticks.
9930                 node.node.timer_tick_occurred();
9931                 check_disconnect_event(node, true);
9932
9933                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9934                 node.node.timer_tick_occurred();
9935                 check_disconnect_event(node, true);
9936         };
9937
9938         create_chan_between_nodes(&nodes[0], &nodes[1]);
9939
9940         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9941         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9942         nodes[0].node.timer_tick_occurred();
9943         check_added_monitors!(&nodes[0], 1);
9944         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9945         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9946         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9947         check_added_monitors!(&nodes[1], 1);
9948
9949         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9950         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9951         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9952         check_added_monitors!(&nodes[0], 1);
9953         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9954         check_added_monitors(&nodes[0], 1);
9955
9956         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9957         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9958         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9959         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9960         check_disconnect(&nodes[1]);
9961
9962         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
9963         //
9964         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
9965         // final `RevokeAndACK` to Bob to complete it.
9966         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9967         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9968         let bob_init = msgs::Init {
9969                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
9970         };
9971         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
9972         let alice_init = msgs::Init {
9973                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9974         };
9975         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
9976
9977         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
9978         // received Bob's yet, so she should disconnect him after reaching
9979         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9980         let alice_channel_reestablish = get_event_msg!(
9981                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
9982         );
9983         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
9984         check_disconnect(&nodes[0]);
9985
9986         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
9987         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
9988                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
9989                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9990                         Some(msg.clone())
9991                 } else {
9992                         None
9993                 }
9994         ).unwrap();
9995         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
9996
9997         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
9998         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9999                 nodes[0].node.timer_tick_occurred();
10000                 check_disconnect_event(&nodes[0], false);
10001         }
10002
10003         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10004         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10005         check_disconnect(&nodes[1]);
10006
10007         // Finally, have Bob process the last message.
10008         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10009         check_added_monitors(&nodes[1], 1);
10010
10011         // At this point, neither node should attempt to disconnect each other, since they aren't
10012         // waiting on any messages.
10013         for node in &nodes {
10014                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10015                         node.node.timer_tick_occurred();
10016                         check_disconnect_event(node, false);
10017                 }
10018         }
10019 }